jweinst1
4/7/2017 - 6:24 AM

example of hashmap in rust in struct

example of hashmap in rust in struct

use std::collections::HashMap;


//hashmap embedded in struct example


struct Env {
    vars: HashMap<String, i32>
}

impl Env {

    fn new() -> Env {
        Env{vars:HashMap::new()}
    }
    
    fn get(&self, key:String) -> i32 {
        match self.vars.get(&key) {
            Some(i) => *i,
            _ => 0
        }
    }
    
    fn set(&mut self, key:String, val:i32) {
        self.vars.insert(key, val);
    }
    
    fn has(&self, key:String) -> bool {
        self.vars.contains_key(&key)
    }
    
    fn del(&mut self, key:String) {
        self.vars.remove(&key);
    }
}

fn main() {
   let mut a = Env::new();
   a.set("foo".to_string(), 4);
   println!("foo is {}", a.get("foo".to_string()));
   println!("foo is {}", a.get("foo".to_string()));
   a.del("foo".to_string());
   println!("foo has {}", a.has("foo".to_string()));
}