走进Rust:HashMap集合
Rust大约 908 字新建
通过宏新建一个HashMap
对象。
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
通过构造函数新建一个HashMap
对象。
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
for (key, value) in &scores {
println!("{}: {}", key, value);
}
更新
覆盖
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Blue"), 25);
println!("{:?}", scores);
只在键没有对应值时插入
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);
根据旧值更新一个值
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);
阅读 344 · 发布于 2020-07-16
————        END        ————
扫描下方二维码关注公众号和小程序↓↓↓

昵称: