rust_learning/collect/
hashmap.rs1use std::collections::HashMap;
2
3pub fn hashmap_def() {
5 let mut scores = HashMap::new();
9
10 scores.insert(String::from("Blue"), 10);
11 scores.insert(String::from("Yellow"), 50);
12
13 let team_name = String::from("Blue");
14 let score = scores.get(&team_name);
18 match score {
19 Some(score) => println!("{:?}", score),
20 None => println!("None"),
21 }
22
23 for (k, v) in &scores {
25 println!("{:?},{:?}", k, v)
26 }
27
28 let field_name = String::from("Favorite color");
31 let field_value = String::from("Blue");
32
33 let mut map = HashMap::new();
34 map.insert(field_name, field_value);
35 let mut scores = HashMap::new();
43 scores.insert(String::from("Blue"), 10);
45 scores.insert(String::from("Blue"), 25);
46 println!("{scores:?}");
47
48 let mut scores = HashMap::new();
50 scores.insert(String::from("Blue"), 10);
51 scores.entry(String::from("Yellow")).or_insert(50);
54 scores.entry(String::from("Blue")).or_insert(50);
55 println!("{scores:?}");
56
57 let text = "hello world wonderful world";
59
60 let mut map = HashMap::new();
61 for word in text.split_whitespace() {
62 let count = map.entry(word).or_insert(0);
64 *count += 1;
65 }
66 println!("{map:?}");
67}