3.3 rust HashMap
The typeHashMap<K, V>
stores a mapping of keys of typeK
to values of typeV
. It does this via ahashing 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. ThisHashMap
has keys of typeString
and values of typei32
. 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 beSome(&10)
. The result is wrapped inSome
becauseget
returns anOption<&V>
; if there’s no value for that key in the hash map,get
will returnNone
$ 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)