The type HashMap<K, V>
stores a mapping of keys of type K
to values of type V
. It does this via a hashing function, which determines how it places these keys and values into memory.
use std::collections::HashMap; pub fn add1(){ let mut scores = HashMap::new(); scores.insert(String::from("Blue"),10); scores.insert(String::from("Yellow"),50); }
Just like vectors, hash maps store their data on the heap. This HashMap
has keys of type String
and values of type i32
. Like vectors, hash maps are homogeneous: all of the keys must have the same type, and all of the values must have the same type.
pub fn get_map(){ let teams = vec![String::from("Blue"), String::from("Yellow")]; let initial_scores = vec![10, 50]; let _scores: HashMap<_, _> = teams.into_iter().zip(initial_scores.into_iter()).collect(); }
Hash Maps and Ownership
简单类型复制,复合类型移动并具有ownership关系,引用类型除外
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); // field_name and field_value are invalid at this point, try using them and // see what compiler error you get! }
We aren’t able to use the variables field_name
and field_value
after they’ve been moved into the hash map with the call to insert
.
If we insert references to values into the hash map, the values won’t be moved into the hash map. The values that the references point to must be valid for at least as long as the hash map is valid.
Accessing Values in a Hash Map
pub fn m1(){ let mut scores = HashMap::new(); scores.insert(String::from("Blue"),10); scores.insert(String::from("Yellow"),50); let team_name = String::from("Blue"); let score = scores.get(&team_name); println!("{:?}",score); println!("--------------------------"); for (key, value) in &scores { let val = value + 1; println!("{}: {}", key, val); } }
Here, score
will have the value that’s associated with the Blue team, and the result will be Some(&10)
. The result is wrapped in Some
because get
returns an Option<&V>
; if there’s no value for that key in the hash map, get
will return None
$ cargo run Compiling a_map v0.1.0 (/opt/wks/rust/a_map) Finished dev [unoptimized + debuginfo] target(s) in 0.28s Running `target/debug/a_map` ------------------ Some(10) -------------------------- Yellow: 51 Blue: 11
Updating a Hash Map
//存在就覆盖 pub fn m2(){ let mut scores = HashMap::new(); scores.insert(String::from("Blue"),10); scores.insert(String::from("Blue"),50); let team_name = String::from("Blue"); let score = scores.get(&team_name); println!("{:?}",score); }
Some(50)
//存在就跳过 pub fn m3(){ let mut scores = HashMap::new(); scores.insert(String::from("Blue"),10); scores.entry(String::from("Blue")).or_insert(50); let team_name = String::from("Blue"); let score = scores.get(&team_name); println!("{:?}",score); }
Some(10)