Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::any::{Any, TypeId};
- use std::cell::*;
- use std::collections::hash_map::ValuesMut;
- use std::collections::{HashMap, HashSet};
- pub trait TypeErasedTrait: std::fmt::Debug + Any {
- }
- pub trait InsideType: std::fmt::Debug {}
- #[derive(Debug)]
- pub struct RealType(i32);
- impl InsideType for RealType { }
- #[derive(Debug)]
- pub struct ConcreteObject<T> where T: InsideType {
- field: T,
- }
- impl<T> TypeErasedTrait for ConcreteObject<T> where T: InsideType + 'static {
- }
- #[derive(Debug)]
- pub struct Builder {
- objects: HashMap<i32, RefCell<Box<dyn TypeErasedTrait>>>,
- }
- fn main() {
- let mut builder = Builder { objects: Default::default() };
- let obj = ConcreteObject { field: RealType(5) };
- builder.objects.insert(0, RefCell::new(Box::new( obj )) );
- {
- let ref_cell = builder.objects.get(&0).unwrap();
- let mut ref_mut = ref_cell.borrow_mut();
- let something = ref_mut.downcast_mut::<ConcreteObject<RealType>>().unwrap();
- println!("{:?}", something.field);
- }
- }
Add Comment
Please, Sign In to add comment