Rust 入门 - HashMap

导入库

use std::collections::HashMap;

使用

let mut scores = HashMap::new();
scores.insert("bad".to_string(), 10);
scores.insert("googd".to_string(), 100);
println!("scores = {:#?}", scores);

vector 和 hashmap 数据都在堆上

用队伍列表和分数列表创建哈希 map

let teams = vec!["blue".to_string(), "red".to_string()];
let scores = vec![10, 50];
let res: HashMap<_, _> = teams.iter().zip(scores.iter()).collect();
println!("res = {:#?}", res);

哈希 map 和所有权

对于像 i32 这样的实现了 Copy trait 的类型,其值可以拷贝进哈希 map。对于像 String 这样拥有所有权的值,其值将被移动而哈希 map 会成为这些值的所有者

let s1 = "hello".to_string();
let s2 = "world".to_string();
let mut map = HashMap::new();
map.insert(s1, s2);
// println!("s1 = {}, s2= {}", s1, s2); 被借用
println!("map = {:#?}", map);

访问哈希 map 中的值

let mut res = HashMap::new();
res.insert("good".to_string(), 100);
res.insert("bad".to_string(), 10);
let k = "good".to_string();
let v = res.get(&k);
match v {
    Some(value) => println!("value = {}", value),
    None => println!("none"),
}

for (key, value) in &res {
    println!("{}: {}", key, value);
}

只在键没有对应值时插入

let mut scores = HashMap::new();
scores.insert("b".to_string(), 100);
scores.entry("b".to_string()).or_insert(10);
scores.entry("r".to_string()).or_insert(90);
println!("scores = {:#?}", 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 = {:#?}", map);

你可能感兴趣的:(Rust 入门 - HashMap)