1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| use std::collections::HashMap;
fn main() { let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Red"), 20); let vec = vec![("Blue", 10), ("Red", 20)]; let map: HashMap<_, _> = vec.into_iter().collect();
let team_name = String::from("Blue"); let score = scores.get(&team_name).copied().unwrap_or(0);
for (key, value) in &scores { println!("{} : {}", key, value); }
scores.insert(String::from("Blue"), 30); scores.insert(String::from("Blue"), 35); for (key, value) in &scores { println!("{} : {}", key, value); }
scores.entry(String::from("Yellow")).or_insert(10); scores.entry(String::from("Blue")).or_insert(50);
for (key, value) in &scores { println!("{} : {}", key, value); }
let text = "hello world world wonderful world"; let mut map = HashMap::new(); for word in text.split_whitespace() { let count = map.entry(word).or_insert(0); *count += 1; } println!("{map:#?}");
}
|