HashMap是以键值对的形式存储数据,一个键(key)对应一个值(value),HashMap的内部实现使用了Hash函数,Hash函数决定了如何在内存中存放key和value。HashMap适用场景为:通过K(任何类型)来寻找数据,而不是通过索引。
use std::collections::HashMap; fn main() { let mut scopes = HashMap::new(); scopes.insert(String::from("Blue"), 10); scopes.insert(String::from("Yellow"), 50); }
HashMap使用比较少,所以不在prelude中。如需要使用HashMap,需要手动引入。标准库对HashMap的支持也比较少,没有内置的宏来创建HashMap。HashMap的数据存放在heap内存上。
use std::collections::HashMap; fn main() { let teams = vec![String::from("Blue"), String::from("Yellow")]; let intial_scores = vec![10, 50]; // 堆代码 duidaima.com // zip函数有拉链的意思,将两个数组拉到一起,在使用 collect 方法集合数据,最后指定生成的集合数据为 HashMap let scores: HashMap<_, _> = teams.iter().zip(intial_scores.iter()).collect(); }三. HashMap和所有权
如果将值的引用插入到HashMap,值本身不会移动,在HashMap有效的期间,被引用的值必须保持有效。
use std::collections::HashMap; fn main() { let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 10); let team_name = String::from("Blue"); let scores = scores.get(&team_name); match scores { Some(s) => println!("{}", s), None => println!("team not exits"), } }五. 遍历HashMap
use std::collections::HashMap; fn main() { let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 10); for (k, v) in &scopes { println!("{}: {}", K, v); } }