fn main() {
// definition
use std::collections::HashMap;
let mut scores = HashMap::new();
// insert
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
let key = String::from("key");
scores.insert(key, 2); // key丧失所有权
// definition 2
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect();
// get
let score = scores.get(&"Blue".to_string());
// tranverse
for (key, value) in &scores {
println!("{}: {}", key, value);
}
// update
// 直接覆盖
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Blue"), 25);
println!("直接覆盖 {:?}", scores); // blue 25
// 没有键时插入
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.entry(String::from("Yellow")).or_insert(50);
scores.entry(String::from("Blue")).or_insert(50);
println!("{:?}", scores); // blue 10, yellow 50
// 根据旧值更新新值
let text = "hello 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); // world:2, hello:1, wonderful: 1
// delete
m.remove(&k);
}