Rust 编程语言中的 HashMap


HashMap 是一个重要的数据结构,因为它允许我们在键值对中存储数据。在 Rust 中,HashMap 按键存储值。

HashMap 键可以是布尔值整数字符串或实现EqHash 特性的任何其他数据类型。

HashMap 可以增大,当空间变得过于大时,它们也可以自行缩小。

我们可以通过多种方式创建一个 HashMap,我们既可以使用HashMap::with_capacity(uint) 也可以使用 HashMap::new()。

以下是 HashMap 支持的方法

  • 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()` returns `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()` returns an iterator that yields
   // (&'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?

更新时间:2021-04-03

浏览量:524

启动你的 职业生涯

完成课程,获得认证

开始
广告