Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // If we make objects owned by the container then we can return references to those objects without lifetime problems.
- use std::any::{Any, TypeId};
- use std::collections::HashMap;
- pub struct MultiTypeContainer<'a> {
- objects: HashMap<TypeId, Vec<Box<dyn Any + 'a>>>,
- }
- impl<'a> MultiTypeContainer<'a> {
- pub fn new() -> Self {
- MultiTypeContainer {
- objects: HashMap::new(),
- }
- }
- pub fn add<T: Any + 'a>(&mut self, object: T) -> &T {
- let type_id = TypeId::of::<T>();
- let boxed_obj = Box::new(object) as Box<dyn Any + 'a>;
- let vec = self.objects.entry(type_id).or_insert_with(Vec::new);
- vec.push(boxed_obj);
- let last_index = vec.len() - 1;
- vec[last_index]
- .downcast_ref::<T>()
- .expect("Failed to downcast Box<dyn Any> to &T")
- }
- }
- fn main() {
- let mut container = MultiTypeContainer::new();
- let string_ref = container.add("Hello, World!".to_string());
- let int_ref = container.add(42);
- println!("String object in container: {}", string_ref);
- println!("Integer object in container: {}", int_ref);
- }
Advertisement
Advertisement