在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
The type 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
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 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 Mappub 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, $ 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)
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论