]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/std/hash.md
New upstream version 1.25.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / std / hash.md
1 # HashMap
2
3 Where vectors store values by an integer index, `HashMap`s store values by key.
4 `HashMap` keys can be booleans, integers, strings,
5 or any other type that implements the `Eq` and `Hash` traits.
6 More on this in the next section.
7
8 Like vectors, `HashMap`s are growable, but HashMaps can also shrink themselves
9 when they have excess space.
10 You can create a HashMap with a certain starting capacity using
11 `HashMap::with_capacity(uint)`, or use `HashMap::new()` to get a HashMap
12 with a default initial capacity (recommended).
13
14 ```rust,editable
15 use std::collections::HashMap;
16
17 fn call(number: &str) -> &str {
18 match number {
19 "798-1364" => "We're sorry, the call cannot be completed as dialed.
20 Please hang up and try again.",
21 "645-7689" => "Hello, this is Mr. Awesome's Pizza. My name is Fred.
22 What can I get for you today?",
23 _ => "Hi! Who is this again?"
24 }
25 }
26
27 fn main() {
28 let mut contacts = HashMap::new();
29
30 contacts.insert("Daniel", "798-1364");
31 contacts.insert("Ashley", "645-7689");
32 contacts.insert("Katie", "435-8291");
33 contacts.insert("Robert", "956-1745");
34
35 // Takes a reference and returns Option<&V>
36 match contacts.get(&"Daniel") {
37 Some(&number) => println!("Calling Daniel: {}", call(number)),
38 _ => println!("Don't have Daniel's number."),
39 }
40
41 // `HashMap::insert()` returns `None`
42 // if the inserted value is new, `Some(value)` otherwise
43 contacts.insert("Daniel", "164-6743");
44
45 match contacts.get(&"Ashley") {
46 Some(&number) => println!("Calling Ashley: {}", call(number)),
47 _ => println!("Don't have Ashley's number."),
48 }
49
50 contacts.remove(&"Ashley");
51
52 // `HashMap::iter()` returns an iterator that yields
53 // (&'a key, &'a value) pairs in arbitrary order.
54 for (contact, &number) in contacts.iter() {
55 println!("Calling {}: {}", contact, call(number));
56 }
57 }
58 ```
59
60 For more information on how hashing and hash maps
61 (sometimes called hash tables) work, have a look at
62 [Hash Table Wikipedia][wiki-hash]
63
64 [wiki-hash]: https://en.wikipedia.org/wiki/Hash_table