哈希映射
向量使用整数索引存储值,而 HashMap
使用键存储值。 HashMap
的键可以是布尔值、整数、字符串或任何实现了 Eq
和 Hash
特性的类型。下一节将对此进行详细介绍。
与向量类似,HashMap
也是可增长的,但 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)); } }
有关哈希和哈希映射(有时称为哈希表)工作原理的更多信息,请参阅哈希表维基百科