1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//1.HashMap<K,V>
//2.创建HashMap
//3.读取
//4.遍历
//5.更新
us std::collections::HashMap;

fn main() {
//2.
let mut scoures: HashMap<String,i32> = HahsMap::new();
scores.insert(String::from("Blue"),10);
scores.insert(String::from("Red"),20);

let keys = vec![String::from("Blue"),String::from("Red")];
let value = vec![10,20];
let scores: HashMap<_,_> = keys.iter().zip(values.iter()).collect();//HashMap
//当中的<_,_>表示这里有这样的值,但是我们不关心值的类型。
//3.
let k = String::from("Blue");
//let v = scores.get(&k); //v = 10
//不能够直接打印,因为get输出的为Option类型,需要使用模式匹配或者if let
//println!("Blue = {}",v);
if let Some(v) = scores.get(&k) { //get 返回一个Option类型
println!("Blue = {}",v);
}

let k = String::from("yellow");
let v = scores.get(&k);
match v {
Some(value) => println!("Blue = {}",value),
None => println!("None"),
}

//4.遍历:顺序是任意的
for (key,value) in &scores {
println!("{},{}",key,value);
}
//5.
//直接插入
let mut ss = HashMap::new();
ss.insert(String::from("one"),1);
ss.insert(String::from("two"),2);
ss.insert(String::from("three"),3);
//同名会覆盖
ss.insert(String::from("one"),3);
println!("{:?}",ss);

//键不存在时插入
let mut ss1 = HashMap::new();
ss1.insert(String::from("one"),1);
ss1.insert(String::from("two"),2);
ss1.insert(String::from("three"),3);
ss1.entry(String::from("one")).or_insert(3);//只有键值不存在才插入
println!("{:?}",ss1);

//根据旧值来更新一个值
let text = "Hello world wonderful world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let mut count = map.entry(word).or_insert(0);
*count += 1;
}
}