Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::collections::HashMap;
- use std::any::Any;
- trait FirstTrait {
- fn get_name(&self) -> &String;
- }
- trait SecondTrait {
- fn get_second_name(&self) -> &String;
- }
- struct First {
- name: String,
- }
- impl FirstTrait for First {
- fn get_name(&self) -> &String {
- &self.name
- }
- }
- struct Second {
- name: String,
- }
- impl FirstTrait for Second {
- fn get_name(&self) -> &String {
- &self.name
- }
- }
- impl SecondTrait for Second {
- fn get_second_name(&self) -> &String {
- &self.name
- }
- }
- struct Holder<'a> {
- services: HashMap<std::any::TypeId, &'a Box<Any>>,
- }
- impl<'a> Holder<'a> {
- fn new() -> Holder<'a> {
- Holder { services: HashMap::new() }
- }
- fn register(&mut self, id: std::any::TypeId, service: &'a Box<Any>) {
- self.services.insert(id, service);
- }
- fn get(&self, id: std::any::TypeId) -> &Box<Any> {
- self.services.get(&id).unwrap()
- }
- }
- fn main() {
- let a = Box::new(First { name: "First".to_string() });
- let b = a as Box<FirstTrait>;
- let typeid = get_type_id(&b);
- let c: Box<Any> = Box::new(b);
- let a1 = Box::new(Second { name: "Second".to_string() });
- let b1 = a1 as Box<SecondTrait>;
- let typeid1 = get_type_id(&b1);
- let c1: Box<Any> = Box::new(b1);
- let mut h = Holder::new();
- h.register(typeid, &c);
- h.register(typeid1, &c1);
- let gg = h.get(typeid);
- let g = gg.downcast_ref::<Box<FirstTrait>>().unwrap();
- println!("{}", g.get_name());
- let gg1 = h.get(typeid1);
- let g1 = gg1.downcast_ref::<Box<SecondTrait>>().unwrap();
- println!("{}", g1.get_second_name());
- }
- fn get_type_id<T: std::any::Any>(_: &T) -> std::any::TypeId {
- std::any::TypeId::of::<T>()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement