add code sample

This commit is contained in:
Robin Müller 2022-09-10 14:10:18 +02:00
parent f5a45c008e
commit 65c423bdd2

View File

@ -0,0 +1,54 @@
use std::sync::{Arc, Mutex};
trait ProvidesFoo {
fn magic(&mut self);
}
struct Foo {
magic_value: u32
}
impl Default for Foo {
fn default() -> Self {
Self {magic_value: 42}
}
}
impl ProvidesFoo for Foo {
fn magic(&mut self) {
println!("ProvidesFoo magic");
}
}
pub type SharedFooConcrete = Arc<Mutex<Box<Foo>>>;
pub type SharedFooTraitObj = Arc<Mutex<Box<dyn ProvidesFoo + Send + Sync>>>;
struct FooProvider {
foo_as_trait_obj: SharedFooTraitObj
}
impl FooProvider {
fn magic_and_then_some(&mut self) {
let mut fooguard = self.foo_as_trait_obj.lock().unwrap();
fooguard.magic();
println!("Additional magic");
}
}
fn uses_shared_foo_boxed_trait_obj(foo: SharedFooTraitObj) {
let mut foo_provider = FooProvider {
foo_as_trait_obj: foo
};
foo_provider.magic_and_then_some();
}
fn uses_shared_foo_concrete(foo: SharedFooConcrete) {
let mut fooguard = foo.lock().unwrap();
fooguard.magic();
}
fn main() {
let shared_foo = Arc::new(Mutex::new(Box::new(Foo::default())));
uses_shared_foo_concrete(shared_foo.clone());
uses_shared_foo_boxed_trait_obj(shared_foo);
}