Rust 编程中的 HashMap
rust programmingserver side programmingprogramming
HashMap 是一种重要的数据结构,因为它允许我们将数据存储在键值对中。在 Rust 中,HashMap 按键存储值。
HashMap 键可以是 Boolean、Integer、strings 或任何其他实现 Eq 和 Hash 特征的数据类型。
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?