Skip to content

1. 什么是HashMap

形如HashMap<k,v>用于存储k键、v值的数据结构的映射。映射关系的实现通过哈希函数实现,其中k可以为任意类型数据。

2.基本操作

2.1 创建

rust
use std::collections::HashMap;


//创建一个`HashMap<String, String>`的空HashMap
let mut book_reviews = HashMap::new();

2.2 插入元素

rust
// 插入元素
book_reviews.insert(
    "Adventures of Huckleberry Finn".to_string(),
    "My favorite book.".to_string(),
);
book_reviews.insert(
    "Grimms' Fairy Tales".to_string(),
    "Masterpiece.".to_string(),
);
book_reviews.insert(
    "Pride and Prejudice".to_string(),
    "Very enjoyable.".to_string(),
);
book_reviews.insert(
    "The Adventures of Sherlock Holmes".to_string(),
    "Eye lyked it alot.".to_string(),
);

2.3 更新元素

rust
//更新元素
book_reviews.insert("Pride and Prejudice","lovable");

//不存在特定key对应值时才插入元素
book_reviews.entry("old man and see").or_insert("thinking")

2.4 删除元素

rust
// 移除元素
book_reviews.remove("The Adventures of Sherlock Holmes");

2.5 获取元素

rust
//获取key对应值
let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
for &book in &to_find {
    match book_reviews.get(book) {
        Some(review) => println!("{book}: {review}"),
        None => println!("{book} is unreviewed.")
    }
}

2.6 遍历元素

rust
// 遍历HashMap
for (book, review) in &book_reviews {
    println!("{book}: \"{review}\"");
}

2.7 其他操作

rust

//校验元素的存在性
if !book_reviews.contains_key("Les Misérables") {
    println!("We've got {} reviews, but Les Misérables ain't one.",
             book_reviews.len());
}

// key不存在时,程序会panic
println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);

//使用zip整合vec为HashMap
let teams  = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];

let mut scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect();

println!("{:?}",scores);//{"Blue":10,"Yellow":50}

提示

在 Rust 中,zip 操作将两个迭代器合并成一个迭代器,该迭代器会按顺序生成其元素的对(元组)。Rust 标准库实现了 FromIterator<(K, V)> for HashMap<K, V>,所以 .collect() 可以直接把由二元元组 (K, V) 组成的 zip 迭代器转换为 HashMap

3. HashMap的所有权

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

rust

#![allow(unused)]
fn main() {
use std::collections::HashMap;

let field_name = String::from("Favorite color");
let field_value = String::from("Blue");

let mut map = HashMap::new();
map.insert(field_name, field_value);
  
println!("{}",filed_name)
// 这里 field_name 和 field_value 不再有效,
// 尝试使用它们看看会出现什么编译错误!
}

4.哈希函数

HashMap 默认使用一种 “密码学安全的”(“cryptographically strong” )1 哈希函数,它可以抵抗拒绝服务(Denial of Service, DoS)攻击。然而这并不是可用的最快的算法,不过为了更高的安全性值得付出一些性能的代价。如果性能监测显示此哈希函数非常慢,以致于你无法接受,你可以指定一个不同的 hasher 来切换为其它函数。hasher 是一个实现了 BuildHasher trait 的类型。