Advertisement
umuro

Untitled

Mar 22nd, 2023
1,328
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.15 KB | Software | 0 0
  1. // If we make objects owned by the container then we can return references to those objects without lifetime problems.
  2.  
  3. use std::any::{Any, TypeId};
  4. use std::collections::HashMap;
  5.  
  6. pub struct MultiTypeContainer<'a> {
  7.    objects: HashMap<TypeId, Vec<Box<dyn Any + 'a>>>,
  8. }
  9.  
  10. impl<'a> MultiTypeContainer<'a> {
  11.     pub fn new() -> Self {
  12.         MultiTypeContainer {
  13.             objects: HashMap::new(),
  14.         }
  15.     }
  16.  
  17.     pub fn add<T: Any + 'a>(&mut self, object: T) -> &T {
  18.        let type_id = TypeId::of::<T>();
  19.        let boxed_obj = Box::new(object) as Box<dyn Any + 'a>;
  20.  
  21.         let vec = self.objects.entry(type_id).or_insert_with(Vec::new);
  22.         vec.push(boxed_obj);
  23.  
  24.         let last_index = vec.len() - 1;
  25.  
  26.         vec[last_index]
  27.             .downcast_ref::<T>()
  28.             .expect("Failed to downcast Box<dyn Any> to &T")
  29.     }
  30. }
  31.  
  32. fn main() {
  33.     let mut container = MultiTypeContainer::new();
  34.  
  35.     let string_ref = container.add("Hello, World!".to_string());
  36.     let int_ref = container.add(42);
  37.  
  38.     println!("String object in container: {}", string_ref);
  39.     println!("Integer object in container: {}", int_ref);
  40. }
  41.  
Tags: rust lifetime
Advertisement
Comments
  • Ima3ine
    1 year
    Comment was deleted
Add Comment
Please, Sign In to add comment
Advertisement