1 | extern crate downcast; |
2 | |
3 | // careful: do not combine downcast_sync! with downcast::Any, you will get `size not known at compile time` errors |
4 | use downcast::{downcast_sync, AnySync}; |
5 | use std::sync::Arc; |
6 | |
7 | /* Trait */ |
8 | |
9 | trait Service: AnySync { |
10 | fn what_am_i(&self); |
11 | } |
12 | |
13 | downcast_sync!(dyn Service); |
14 | |
15 | /* Impl */ |
16 | |
17 | struct Database {} |
18 | |
19 | impl Service for Database { |
20 | fn what_am_i(&self){ |
21 | println!("I'm a database!" ); |
22 | } |
23 | } |
24 | |
25 | impl Database { |
26 | fn purge_data(&self) { |
27 | println!("Database has been purged! Goodbye, data!" ) |
28 | } |
29 | } |
30 | |
31 | fn main(){ |
32 | let service: Arc<dyn Service> = Arc::new(Database{}); |
33 | service.what_am_i(); |
34 | { |
35 | let db = service.downcast_ref::<Database>().unwrap(); |
36 | db.purge_data(); |
37 | } |
38 | let db: Arc<Database> = service.downcast_arc::<Database>().ok().unwrap(); |
39 | db.purge_data(); |
40 | } |
41 | |
42 | |