Skip to content

Instantly share code, notes, and snippets.

@gliheng
Created February 5, 2018 02:30
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 gliheng/824b1ff5c66914b9a057b46732173be7 to your computer and use it in GitHub Desktop.
Save gliheng/824b1ff5c66914b9a057b46732173be7 to your computer and use it in GitHub Desktop.
use dynamic typing in rust
use std::collections::HashMap;
use std::any::Any;
fn main() {
let mut h: HashMap<&str, &Any> = HashMap::new();
h.insert("width", &321_i32);
h.insert("msg", &"hello");
if let Some(v) = h.get("width") {
match v.downcast_ref::<i32>() {
Some(v) => {
println!("width: {}", v);
},
None => {
println!("noop");
}
}
}
if let Some(v) = h.get("msg") {
match v.downcast_ref::<&str>() {
Some(v) => {
println!("msg: {}", v);
},
None => {
println!("noop");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment