add code sample
This commit is contained in:
parent
f5a45c008e
commit
65c423bdd2
54
fsrc-example/src/bin/test2.rs
Normal file
54
fsrc-example/src/bin/test2.rs
Normal 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);
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user