17.7 HashMap
벡터가 정수 색인으로 값을 저장하는 것처럼 HashMap은 키별로 값을 저장한다. HashMap의 키는 boolean, 정수, 문자열 또는 Eq와 Hash trait을 구현하는 다른 유형이 될 수 있다. 이에 대한 자세한 내용은 다음 섹션 참고.
벡터와 마찬가지로 HashMap도 확장 가능하지만 과도한 공간이 있을 때 HashMaps는 축소 될 수 있습니다. 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");
// 참조를 취하고 Option<&v>를 반환.
match contacts.get(&"Daniel") {
Some(&number) => println!("Calling Daniel: {}", call(number)),
_ => println!("Don't have Daniel's number."),
}
// 삽입된 값이 새 값이면 `HashMap::insert()`는 `None`을 반환.
// 그렇지 않으면 `Some(value)`.
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()`는 임의의 순서로 ('&a key, &'a value) 쌍을
// 산출하는 반복자를 반환.
for (contact, &number) in contacts.iter() {
println!("Calling {}: {}", contact, call(number));
}
}해시 및 해시 맵(해시 테이블이라고도 함)의 작동 방식에 대한 자세한 내용은 여기 참조 Hash Table Wikipedia