Skip to main content

type_map/
type_map.rs

1use std::collections::HashMap;
2
3use zonbi::{AnyZonbi, Cage, Zonbi, ZonbiId};
4
5#[derive(Debug, PartialEq)]
6struct NonCopyI32(i32);
7
8#[derive(Zonbi)]
9struct MyStruct<'a> {
10    val: &'a NonCopyI32,
11}
12
13fn main() {
14    let a = NonCopyI32(42);
15
16    with_zonbi(&a);
17}
18
19fn with_zonbi<'a>(a: &'a NonCopyI32) {
20    let my_struct = MyStruct { val: a };
21
22    let mut type_map: HashMap<ZonbiId, Box<dyn AnyZonbi<'a>>> = HashMap::new();
23    let id = ZonbiId::of::<MyStruct>();
24
25    type_map.insert(id, Box::new(Cage::new(my_struct)));
26
27    let r: &MyStruct<'a> = type_map[&id].downcast_ref::<MyStruct<'a>>().unwrap();
28    assert_eq!(r.val, &NonCopyI32(42));
29    println!("{:?}", r.val);
30}
31
32// Try commenting the code out
33// fn fails<'a>(a: &'a NonCopyI32) {
34//     use std::any::{Any, TypeId};
35
36//     let my_struct = MyStruct { val: a };
37
38//     let mut type_map: HashMap<TypeId, Box<dyn Any>> = HashMap::new();
39//     let id = TypeId::of::<MyStruct>();
40//     type_map.insert(id, Box::new(my_struct));
41// }