HashMap
向量通过整数索引存储值,而 HashMap
则通过键存储值。HashMap
的键可以是布尔值、整数、字符串或任何其他实现了 Eq
和 Hash
特性的类型。下一节会详细介绍。
与向量类似,HashMap
是可增长的,但当它们有多余空间时也可以自行收缩。你可以使用 HashMap::with_capacity(uint)
创建一个具有特定起始容量的 HashMap,或者使用 HashMap::new()
获取一个具有默认初始容量的 HashMap(推荐)。
use std::collections::HashMap; fn call(number: &str) -> &str { match number { "798-1364" => "We're sorry, the call cannot be completed as dialed. Please hang up and try again.", "645-7689" => "Hello, this is Mr. Awesome's Pizza. My name is Fred. What can I get for you today?", _ => "Hi! Who is this again?" } } fn main() { let mut contacts = HashMap::new(); contacts.insert("Daniel", "798-1364"); contacts.insert("Ashley", "645-7689"); contacts.insert("Katie", "435-8291"); contacts.insert("Robert", "956-1745"); // Takes a reference and returns Option<&V> match contacts.get(&"Daniel") { Some(&number) => println!("Calling Daniel: {}", call(number)), _ => println!("Don't have Daniel's number."), } // `HashMap::insert()` returns `None` // if the inserted value is new, `Some(value)` otherwise contacts.insert("Daniel", "164-6743"); match contacts.get(&"Ashley") { Some(&number) => println!("Calling Ashley: {}", call(number)), _ => println!("Don't have Ashley's number."), } contacts.remove(&"Ashley"); // `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)); } }
有关哈希和哈希映射(有时称为哈希表)如何工作的更多信息,请查看哈希表维基百科