概述
哈希map(hash map)是一种基于哈希表的集合类型,用于存储键值对。提供了快速的查找,插入和删除的操作。
HashMap<k, v>类型存储了一个键类型K对应一个值类型V的映射。
创建一个哈希map
在Rust中,使用标准库中的HashMap来实现哈希表。需要在代码中引入std::collections::HashMap模块。
//记录两支队伍的分数,分别是蓝队和黄队。蓝队有10分,黄队有50分
use std::collectons::HashMap;
let mut scores = HashMap::new(); //创建一个空的HashMap
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
访问哈希map中的值
通过get方法并提供对应的键来从哈希map中获取值。
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("blue"), 10);
scores.insert(String::from("Yellow"), 50);
let team_name = String::from("blue");
let score = scores.get(&team_name).copied().unwrap_or(0);
遍历哈希map的键值对
use std::collections::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}");
}
//输出结果:
Yellow: 50
Blue: 10
更新哈希map
//覆盖一个值
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Blue"), 25); //原始的值被25覆盖了
println!("{:?}", scores);
只有键灭有对应值时插入键值对
当检查某个特定的键是否已经存在于哈希map中并进行如下操作:如果哈希map中键已经存在则不做任何操作,如果不存在则连同值一块插入。
use std::collections::HashMap;
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);
//输出结果:
{"Yellow": 50, "Blue": 10}
第一个entry调用会插入黄队和值50,因为没有黄队和值。第二个entry调用不会改变哈希map,因为蓝队已经有了值10。
根据旧值更新一个值
use std::collections::HashMap;
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}
split_whitespace方法返回一个由空格分隔text值子slice的迭代器。
or_insert方法返回这个键的值的一个可变引用(&mut V)。我们将这个可变引用储存在count变量中,所以为了赋值必须首先使用星号 (*) 解引用count。