Skip to main content

smap/
lib.rs

1use std::collections::HashMap;
2
3pub struct Dict {
4    map: HashMap<String, String>,
5}
6
7impl Dict {
8    pub fn new() -> Self {
9        Self {
10            map: HashMap::new()
11        }
12    }
13
14    /// dict.add(k,v): insert (k,v) into dict
15    /// 
16    /// ```
17    /// e2c.add("john", "123");
18    /// e2c.add("snoopy", "456");
19    /// ```
20    pub fn add(&mut self, k:&str, v:&str) {
21        self.map.insert(k.to_string(), v.to_string());
22    }
23
24    /// dict.get(key): get value for key from dict
25    /// ```
26    /// e2c.get("snoopy");
27    /// ```
28    pub fn get(&mut self, k:&str)->Option<&String> {
29        return self.map.get(k);
30    }
31}
32
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn dict_test() {
40        let mut e2c = Dict::new();
41        e2c.add("a", "一隻");
42        e2c.add("dog", "狗");
43        e2c.add("cat", "貓");
44        e2c.add("chase", "追");
45        e2c.add("bite", "咬");
46        assert!(e2c.get("cat") != None);
47        assert!(e2c.get("xxx") == None);
48    }
49}