Created
February 5, 2018 02:30
-
-
Save gliheng/824b1ff5c66914b9a057b46732173be7 to your computer and use it in GitHub Desktop.
use dynamic typing in rust
This file contains 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::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