You've got your big G's, I've got my hash map

This commit is contained in:
Carol (Nichols || Goulding)
2016-09-26 22:31:27 -04:00
parent c3ddfa5c44
commit d56e5367cb
4 changed files with 42 additions and 42 deletions
+1 -1
View File
@@ -34,7 +34,7 @@
- [Fundamental Collections](ch08-00-fundamental-collections.md)
- [Vectors](ch08-01-vectors.md)
- [Strings](ch08-02-strings.md)
- [HashMaps](ch08-03-hashmaps.md)
- [Hash Maps](ch08-03-hash-maps.md)
- [Error Handling]()
+4 -4
View File
@@ -7,10 +7,10 @@ different capabilities and costs, and choosing an appropriate one for the
situation you're in is a skill you'll develop over time. In this chapter, we'll
go over three collections which are used very often in Rust programs:
* A *Vector* allows us to store a variable number of values next to each other.
* A *String* is a collection of characters. We've seen `String` before, but
we'll talk about it in depth now.
* A *HashMap* allows us to associate a value with a particular key.
* A *vector* allows us to store a variable number of values next to each other.
* A *string* is a collection of characters. We've seen the `String` type
before, but we'll talk about it in depth now.
* A *hash map* allows us to associate a value with a particular key.
There are more specialized variants of each of these data structures for
particular situations, but these are the most fundamental and common. We're
+1 -1
View File
@@ -367,4 +367,4 @@ complexity of strings than we have to handle in other languages, but will
prevent us from having to handle errors involving non-ASCII characters later in
our development lifecycle.
Let's switch to something a bit less complex: HashMap!
Let's switch to something a bit less complex: Hash Map!
@@ -1,19 +1,19 @@
## HashMaps
## Hash Maps
The last of our fundamental collections is the *HashMap*. A `HashMap<K, V>`
stores a mapping of keys of type `K` to values of type `V`. It does this via a
*hashing function*, which determines how it places these keys and values into
memory. Many different programming languges support this kind of data
The last of our fundamental collections is the *hash map*. The type `HashMap<K,
V>` stores a mapping of keys of type `K` to values of type `V`. It does this
via a *hashing function*, which determines how it places these keys and values
into memory. Many different programming languges support this kind of data
structure, but often with a different name: hash, map, object, hash table, or
associative array, just to name a few.
We'll go over the basic API in this chapter, but there are many more goodies
hiding in the functions defined on HashMap by the standard library. As always,
hiding in the functions defined on `HashMap` by the standard library. As always,
check the standard library documentation for more information.
### Creating a HashMap
### Creating a New Hash Map
We can create an empty HashMap with `new`, and add elements with `insert`:
We can create an empty `HashMap` with `new`, and add elements with `insert`:
```rust
use std::collections::HashMap;
@@ -30,12 +30,12 @@ often used, so it has a bit less support from the language. There's no built-in
macro to construct them, for example, and they're not in the prelude, so we
need to add a `use` statement for them.
Just like vectors, HashMaps store their data on the heap. This HashMap has keys
of type `i32` and values of type `&str`. Like vectors, HashMaps are homogenous:
all of the keys must have the same type, and all of the values must have the
same type.
Just like vectors, hash maps store their data on the heap. This `HashMap` has
keys of type `i32` and values of type `&str`. Like vectors, hash maps are
homogenous: all of the keys must have the same type, and all of the values must
have the same type.
If we have a vector of tuples, we can convert it into a HashMap with the
If we have a vector of tuples, we can convert it into a hash map with the
`collect` method. The first element in each tuple will be the key, and the
second element will be the value:
@@ -50,12 +50,12 @@ let map: HashMap<_, _> = data.into_iter().collect();
The type annotation `HashMap<_, _>` is needed here because it's possible to
`collect` into many different data structures, so Rust doesn't know which we
want. For the type parameters for the key and value types, however, we can use
underscores and Rust can infer the types that the HashMap contains based on the
underscores and Rust can infer the types that the hash map contains based on the
types of the data in our vector.
For types that implement the `Copy` trait like `i32` does, the values are
copied into the HashMap. If we insert owned values like `String`, the values
will be moved and the HashMap will be the owner of those values:
copied into the hash map. If we insert owned values like `String`, the values
will be moved and the hash map will be the owner of those values:
```rust
use std::collections::HashMap;
@@ -69,16 +69,16 @@ map.insert(field_name, field_value);
```
We would not be able to use the bindings `field_name` and `field_value` after
they have been moved into the HashMap with the call to `insert`.
they have been moved into the hash map with the call to `insert`.
If we insert references to values, the values themselves will not be moved into
the HashMap. The values that the references point to must be valid for at least
as long as the HashMap is valid, though. We will talk more about these issues
the hash map. The values that the references point to must be valid for at least
as long as the hash map is valid, though. We will talk more about these issues
in the Lifetimes section of Chapter 10.
### Accessing Values in a HashMap
### Accessing Values in a Hash Map
We can get a value out of the HashMap by providing its key to the `get` method:
We can get a value out of the hash map by providing its key to the `get` method:
```rust
use std::collections::HashMap;
@@ -93,10 +93,10 @@ let value = map.get(&2);
Here, `value` will have the value `Some("world")`, since that's the value
associated with the `2` key. "world" is wrapped in `Some` because `get` returns
an `Option<V>`. If there's no value for that key in the HashMap, `get` will
an `Option<V>`. If there's no value for that key in the hash map, `get` will
return `None`.
We can iterate over each key/value pair in a HashMap in a similar manner as we
We can iterate over each key/value pair in a hash map in a similar manner as we
do with vectors, using a `for` loop:
```rust
@@ -119,11 +119,11 @@ This will print:
2: world
```
### Updating a HashMap
### Updating a Hash Map
#### Overwriting a Value
If we insert a key and a value, then insert that key with a different value, the value associated with that key will be replaced. Even though this code calls `insert` twice, the HashMap will only contain one key/value pair, since we're inserting with the key `1` both times:
If we insert a key and a value, then insert that key with a different value, the value associated with that key will be replaced. Even though this code calls `insert` twice, the hash map will only contain one key/value pair, since we're inserting with the key `1` both times:
```rust
use std::collections::HashMap;
@@ -141,7 +141,7 @@ This will print `{1: "Hi There"}`.
#### Only Insert If the Key Has No Value
It's common to want to see if there's some sort of value already stored in the
HashMap for a particular key, and if not, insert a value. HashMaps have a
hash map for a particular key, and if not, insert a value. hash maps have a
special API for this, called `entry`, that takes the key we want to check as an
argument:
@@ -180,14 +180,14 @@ logic ourselves, and in addition, plays more nicely with the borrow checker.
This code will print `{1: "hello", 2: "world"}`. The first call to `entry` will
insert the key `2` with the value "world", since `2` doesn't have a value
already. The second call to `entry` will not change the HashMap since `1`
already. The second call to `entry` will not change the hash map since `1`
already has the value "hello".
#### Update a Value Based on the Old Value
Another common use case for HashMaps is to look up a key's value then update
Another common use case for hash maps is to look up a key's value then update
it, using the old value. For instance, if we wanted to count how many times
each word appeared in some text, we could use a HashMap with the words as keys
each word appeared in some text, we could use a hash map with the words as keys
and increment the value to keep track of how many times we've seen that word.
If this is the first time we've seen a word, we'll first insert the value `0`.
@@ -208,7 +208,7 @@ println!("{:?}", map);
This will print `{"world": 2, "hello": 1, "wonderful": 1}`. The `or_insert`
method actually returns a mutable reference (`&mut V`) to the value in the
HashMap for this key. Here we store that mutable reference in the `count`
hash map for this key. Here we store that mutable reference in the `count`
variable binding, so in order to assign to that value we must first dereference
`count` using the asterisk (`*`). The mutable reference goes out of scope at
the end of the `for` loop, so all of these changes are safe and allowed by the
@@ -216,7 +216,7 @@ borrowing rules.
### Hashing Function
By default, HashMap uses a cryptographically secure hashing function that can
By default, `HashMap` uses a cryptographically secure hashing function that can
provide resistance to Denial of Service (DoS) attacks. This is not the fastest
hashing algorithm out there, but the tradeoff for better security that comes
with the drop in performance is a good default tradeoff to make. If you profile
@@ -227,18 +227,18 @@ be talking about traits and how to implement them in Chapter 10.
## Summary
Vectors, Strings, and HashMaps will take you far in programs where you need to
Vectors, strings, and hash maps will take you far in programs where you need to
store, access, and modify data. Some programs you are now equipped to write and
might want to try include:
* Given a list of integers, use a Vector and return their mean (average),
* Given a list of integers, use a vector and return their mean (average),
median (when sorted, the value in the middle position), and mode (the value
that occurs most often; a HashMap will be helpful here).
* Convert Strings to Pig Latin, where the first consonant of each word gets
that occurs most often; a hash map will be helpful here).
* Convert strings to Pig Latin, where the first consonant of each word gets
moved to the end with an added "ay", so "first" becomes "irst-fay". Words that
start with a vowel get an h instead ("apple" becomes "apple-hay"). Remember
about UTF-8 encoding!
* Using a HashMap and Vectors, create a text interface to allow a user to add
* Using a hash map and vectors, create a text interface to allow a user to add
employee names to a department in the company. For example, "Add Sally to
Engineering" or "Add Ron to Sales". Then let the user retrieve a list of all
people in a department or all people in the company by department, sorted