Created
June 18, 2023 22:11
-
-
Save ajazam/c0c3d1d1095914b4de5769418bb26c7a to your computer and use it in GitHub Desktop.
Hashmap using Any as value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::any::Any; | |
use std::collections::HashMap; | |
#[derive(Debug)] | |
struct Struct1 { | |
pub f1: u32, | |
pub f2: u32, | |
} | |
#[derive(Debug)] | |
struct Struct2 { | |
pub f1: u32, | |
} | |
fn is_struct1(s: &dyn Any) -> bool { | |
s.is::<Struct1>() | |
} | |
fn main() { | |
let mut hm: HashMap<String, &dyn Any> = HashMap::new(); | |
hm.insert(String::from("one"), &Struct1 { f1: 1, f2: 1 }); | |
hm.insert(String::from("two"), &Struct2 { f1: 0 }); | |
println!("contents are {:?}", hm.get("one").unwrap()); | |
let element = *hm.get("one").unwrap(); | |
let str = element.downcast_ref::<Struct1>().unwrap(); | |
println!("{:?}", str); | |
assert!(is_struct1(element)); | |
assert!(is_struct1(&Struct1 { f1: 1, f2: 3 })); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment