哈希Map通过一个哈希函数来实现颜射,决定如何将键和值放入内存中。
准备
use std::collections::HashMap;
1、方法1
let mut scores = HashMap::new();
scores.insert(String::from("blue"), 10);
scores.insert(String::from("yellow"), 50);
println!("{:?}", scores)
2、方法2
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
let scores:HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect();
println!("{:?}", scores)
3、初始化与所有权:
let field_name = String::from("Favorite color");
let field_value = String::from("Blue");
let mut map = HashMap::new();
map.insert(&field_name, field_value); //fileld_name无效
println!("{}, {}", field_name, field_value); //error[E0382]: borrow of moved value: `field_value`
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("blue"), 10);
scores.insert(String::from("yellow"), 50);
println!("{:?}", scores);
println!("get---->{:?}", scores.get("blue"));
for (k, v) in & scores{
println!("{}:{}", k, v)
}
}
get 返回 Option,所以结果被装进 Some;如果某个键在哈希 map 中没有对应的值,get 会返回 None
1、覆盖一个值
当插入一个键时,如果已经有这个键了就直接覆盖,如果没有就创建键
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Blue"), 25);
println!("{:?}", scores);
}
2、只在键没有对应值时插入
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.entry(String::from("Yellow")).or_insert(25);
scores.entry(String::from("Blue")).or_insert(25);
println!("{:?}", scores);
}
3、根据旧值更新值
use std::collections::HashMap;
fn main() {
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)
}
参考:https://kaisery.github.io/trpl-zh-cn/ch08-03-hash-maps.html