jweinst1
4/7/2017 - 6:24 PM

envfinished.rs

use std::collections::HashMap;


//hashmap embedded in struct example


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

impl Env {

    fn new() -> Env {
        Env{vars:HashMap::new(), parent:Vec::with_capacity(1)}
    }
    
    fn create_child(self) -> Env {
        let mut newchild = Env::new();
        newchild.parent.push(self);
        newchild
    }
    
    fn has_parent(&self) -> bool {
        !self.parent.is_empty()
    }
    
    fn get(&self, key:String) -> i32 {
        match self.vars.get(&key) {
            Some(i) => *i,
            _ => return if self.has_parent() {self.parent[0].get(key)} else {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()));
   a.set("foo".to_string(), 4);
   println!("a has parent: {}", a.has_parent());
   let mut b = a.create_child();
   b.set("doo".to_string(), 2);
   println!("retreived from parent env {}", b.get("foo".to_string()));
}

/*
foo is 4
foo is 4
foo has false
a has parent: false
retreived from parent env 4
*/