February 5, 2018 · rust

Dynamic typing in rust

Any trait is a trait that matches any type in rust. Use it as a trait object, allows for dynamic typing.

The following code use Any trait with a HashMap to store anything in it.

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") {
        // a downcast might fail, use a match statement to test it.
        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");
            }
        }
    }
}

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket