hash map:
HashMap<K, V>存储映射关系:类型K 到 类型V的映射;实现中使用hashing函数,决定key和value在内存中如何安置;
创建: hash map存储data在heap上;
using std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blu"), 10);
scores.insert(String::from("Yel"), 50);
或者通过迭代vector元组来构建;
use std::collections::HashMap;
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
let mut scores: HashMap<_, _> =
teams.into_iter().zip(initial_scores.into_iter()).collect();
实现Copy Trait的数据结构,value值被拷贝到hash map中;对于owned类型,值将被移动并且hash map将拥有value;
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);
// field_name and field_value are invalid at this point, try using them and
// see what compiler error you get!
访问:
let team_name = String::from("Blue");
let score = scores.get(&team_name); //被封装尽Some,get方法返回一个Option<&V>
for (key, value) in &scores { //迭代访问;
println!("{}: {}", key, value);
}
更新:
(1)覆盖更新:scores.insert(String::from("Blue"), 25);
(2)非覆盖更新:scores.entry(String::from("Yellow")).or_insert(50);