Skip to content

Instantly share code, notes, and snippets.

@ajazam
Created June 18, 2023 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajazam/c0c3d1d1095914b4de5769418bb26c7a to your computer and use it in GitHub Desktop.
Save ajazam/c0c3d1d1095914b4de5769418bb26c7a to your computer and use it in GitHub Desktop.
Hashmap using Any as value
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