HashMap
HashMap<K, V> 用于保存键值对,类似很多语言中的 dictionary 或 map。
创建 HashMap
src/main.rs
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Alice"), 95);
scores.insert(String::from("Bob"), 82);
println!("{scores:?}");
}
读取值
let score = scores.get("Alice");
get() 返回 Option<&V>:
match scores.get("Alice") {
Some(score) => println!("{score}"),
None => println!("not found"),
}
遍历 HashMap
for (name, score) in &scores {
println!("{name}: {score}");
}
遍历顺序不固定,不要依赖它。
entry
只在 key 不存在时插入:
scores.entry(String::from("Cindy")).or_insert(100);
小结
你需要掌握:
HashMap位于std::collections。insert()插入键值对。get()返回Option。- 遍历顺序不固定。
entry()适合“没有就插入”的场景。