Rust 编程中的 HashMap
HashMap是一种重要的数据结构,因为它允许我们以键值对的形式存储数据。在Rust中,HashMap按键存储值。
HashMap键可以是布尔值、整数、字符串或任何其他实现Eq和Hash特征的数据类型。
HashMap的大小可以增长,当空间变得过多时,它们也可以自行缩小。
我们可以通过多种方式创建HashMap,我们可以使用HashMap::with_capacity(uint)或HashMap::new()。
以下是HashMaps支持的方法:
insert()
get()
remove()
iter()
示例
让我们看一个例子,我们构建一个HashMap并使用上述所有这些操作。
考虑下面显示的示例。
use std::collections::HashMap;
fn call(number: &str) -> &str {
match number {
"798-133" => "We're sorry. Please hang up and try again.",
"645-7698" => "Hello, What can I get for you today?",
_ => "Hi! Who is this again?"
}
}
fn main() {
let mut contacts = HashMap::new();
contacts.insert("Mukul", "798-133");
contacts.insert("Mayank", "645-7698");
contacts.insert("Karina", "435-8291");
contacts.insert("Rahul", "956-1745");
match contacts.get(&"Mukul") {
Some(&number) => println!("Calling Mukul: {}", call(number)),
_ => println!("Don't have Mukul's number."),
}
//`HashMap::insert()`返回`None`
contacts.insert("Mukul", "164-6743");
match contacts.get(&"Mayank") {
Some(&number) => println!("Calling Mayank: {}", call(number)),
_ => println!("Don't have Mayank's number."),
}
contacts.remove(&"Mayank");
//`HashMap::iter()`返回一个迭代器,它产生
// (&'a key, &'a value) pairs in arbitrary order.
for (contact, &number) in contacts.iter() {
println!("Calling {}: {}", contact, call(number));
}
}输出结果Calling Mukul: We're sorry. Please hang up and try again. Calling Mayank: Hello, What can I get for you today? Calling Mukul: Hi! Who is this again? Calling Karina: Hi! Who is this again? Calling Rahul: Hi! Who is this again?