/ Chapter8 / hash_maps / src / main.rs
main.rs
 1  use std::collections::HashMap;
 2  
 3  fn main() {
 4  
 5      // Overwriting a Value
 6      let mut scores = HashMap::new();
 7  
 8      scores.insert(String::from("Blue"), 10);
 9      scores.insert(String::from("Blue"), 25);
10  
11      println!("{:?}", scores);
12  
13      // Adding a Key and Value Only If a Key Isn’t Present
14      let mut scores = HashMap::new();
15      scores.insert(String::from("Blue"), 10);
16  
17      scores.entry(String::from("Yellow")).or_insert(50);
18      scores.entry(String::from("Blue")).or_insert(50);
19  
20      println!("{:?}", scores);
21  
22      // Updating a Value Based on the Old Value
23      let text = "hello world wonderful world";
24  
25      let mut map = HashMap::new();
26  
27      for word in text.split_whitespace() {
28          let count = map.entry(word).or_insert(0);
29          *count += 1;
30      }
31  
32      println!("{:?}", map);
33  
34  
35  }