From 4de58546ae3838c97d5465510ba1db4b01d8a536 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Tue, 19 Jul 2016 17:56:43 -0400 Subject: [PATCH 01/34] some work on collections --- src/SUMMARY.md | 8 +- src/ch09-01-basic-collections.md | 16 ++ src/ch09-02-vectors.md | 307 +++++++++++++++++++++++++++++++ src/ch09-03-strings.md | 13 ++ src/ch09-04-hash-map.md | 15 ++ 5 files changed, 355 insertions(+), 4 deletions(-) create mode 100644 src/ch09-01-basic-collections.md create mode 100644 src/ch09-02-vectors.md create mode 100644 src/ch09-03-strings.md create mode 100644 src/ch09-04-hash-map.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 8e4ad4a8b..fbe7d919e 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -31,10 +31,10 @@ - [Controlling visibility with `pub`](ch07-02-controlling-visibility-with-pub.md) - [Importing names with `use`](ch07-03-importing-names-with-use.md) -- [Basic Collections]() - - [Vectors]() - - [Strings]() - - [`HashMap`]() +- [Basic Collections](ch09-01-basic-collections.md) + - [Vectors](ch09-02-vectors.md) + - [Strings](ch09-03-strings.md) + - [`HashMap`](ch09-04-hash-map.md) - [Error Handling]() diff --git a/src/ch09-01-basic-collections.md b/src/ch09-01-basic-collections.md new file mode 100644 index 000000000..c1fbff98f --- /dev/null +++ b/src/ch09-01-basic-collections.md @@ -0,0 +1,16 @@ +# Basic Collections + +Rust's standard library includes a number of really useful data structures +called 'collections'. Most types represent one specific value, but collections +can contain multiple values inside of them. Each collection has different +capabilities and costs, and chosing 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: + +* *Vector*s allow you to store a variable number of values next to each other. +* We've seen *String*s before, but we'll talk about them some more: they're + collections of characters. +* *HashMap*s allow you to associate a value with a particular key. + +There are more specialized variants of each of these data structures for +special situations, but these ones are the most fundamental. diff --git a/src/ch09-02-vectors.md b/src/ch09-02-vectors.md new file mode 100644 index 000000000..3c2ce7d9c --- /dev/null +++ b/src/ch09-02-vectors.md @@ -0,0 +1,307 @@ +# Vectors + +The first type we'll look at is `Vec`, also known as a 'vector'. Vectors +allow you to store more than one value in a single data structure, next to each +other in memory. + +## Creating a new vector + +To create a new vector, you can call the `new` function: + +```rust +let v: Vec = Vec::new(); +``` + +You'll note that we added a type annotation here. Because we don't actually do +anything with the vector, Rust doesn't know what sort of elements we intend to +store. This is an important point. Vectors are homogenous; they may store many +values, but those values must be all of the same type. Vectors are generic over +the type you store inside them, so we use the angle brackets to tell Rust that +this vector will hold elements of the `i32` type. + +That said, in real code, you very rarely need to do this type annotation. Let's +insert some values to see this in action. To put elements in the vector, we can +use the `push` method: + +```rust +let mut v = Vec::new(); + +v.push(5); +v.push(6); +v.push(7); +v.push(8); +``` + +Since these numbers are `i32`s, Rust can infer the type of the vector, so we +don't need the annotation. That said, creating a vector with some initial +values like this is very common, and so there's a macro to do it for us: + +```rust +let v = vec![5, 6, 7, 8]; +``` + +This macro does the exact same thing as our previous example, but it's much +more convenient. + +How does this all work? Under the hood, vectors look approximately like this: + +```rust,ignore +struct Vec { + data: &mut T, + capacity: usize, + length: usize, +} +``` + +This is not literally true, but will help you gain some intutions about it at +a high level. The actual representation is quite involved, and you can [read a +chapter in the Nomicon][nomicon] for the full details. + +[nomicon]: https://doc.rust-lang.org/stable/nomicon/vec.html + +At a high level, though, this is okay: a vector has a reference to some data, +a capacity, and a length. Let's go through these lines of code, and see how +the vector changes. + +```rust +let mut v = Vec::new(); +# +# v.push(5); +# v.push(6); +# v.push(7); +# v.push(8); +``` + +We've created our new vector. It will look like this: + +```text +Vec { + data: , + capacity: 0, + length: 0, +} +``` + +We don't have anything stored yet, so the vector hasn't made any room for any +elements. Since we don't have any elements, `data` isn't valid either. + +```rust +# let mut v = Vec::new(); +# +v.push(5); +# v.push(6); +# v.push(7); +# v.push(8); +``` + +Next, we insert one value into the vector. `push` looks at the current capacity +and length, and sees that there's no room for this `5` to go. Since there's +currently room for zero elements, it will request enough memory from the +operating system for a single element, and then copy `5` into that memory. It +then updates the internal details, and now they look like this: + +```text +struct Vec { + data:
, + capacity: 1, + length: 1, +} +``` + +Our `data` now points to the start of this memory, and `capacity` and `length` +are both set to one. If they're both set to the same value, what's the +difference? We will see that shortly. But first, let's insert another value +into the vector: + + +```rust +# let mut v = Vec::new(); +# +# v.push(5); +v.push(6); +# v.push(7); +# v.push(8); +``` + +Same thing, we `push` a `6`. And, in this case, the same thing will happen: +`push` looks at the values of `capacity` and `len`, and sees that we don't have +room for a second element. So here's what it does: it requests room for twice +as many elements as we currently have. In this case, that means two elements. +It then copies the existing element over into the new memory allocation, and +then copies the `6` into the next open slot. After updating the internal +values, it now looks like this: + + +```text +struct Vec { + data:
, + capacity: 2, + length: 2, +} +``` + +Our `capacity` and `length` both show two here. Let's try inserting another +elment into the vector: + +```rust +# let mut v = Vec::new(); +# +# v.push(5); +# v.push(6); +v.push(7); +# v.push(8); +``` + +Same story here: `push` looks and sees that our vector is full. However, +this time, something is slightly different. We currently have a capacity of +two elements. So the vector will request memory for double that number of +elements from the operating system: four. But why does it double every time? +We'll learn about that soon. For now, `push` will then copy the first two +elements over to the new memory, copy our `7` onto the end, and then update +the internal state. What's it look like now? + +```text +struct Vec { + data:
, + capacity: 4, + length: 3, +} +``` + +Ah ha! A difference. In essence, `capacity` tracks how much memory we've got +saved away for holding elements. `length` keeps track of how many elements we +are actually storing. Why not just allocate exactly how much we need? In order +to get more heap memory, we have to talk to the operating system, and that's +slower. Not only that, but we have to copy the contents of the vector from the +old memory to the new memory each time. So we make a tradeoff: we allocate a +bit more memory than we need, but in exchange, we get speed. + +We can see this speed the next time we call `push`: + +```rust +# let mut v = Vec::new(); +# +# v.push(5); +# v.push(6); +v.push(7); +# v.push(8); +``` + +Now, `push` looks at the capacity versus the length: we have room for four +elements, but we only have three elements. Perfect! We skip that "request more +memory from the OS and copy everything" business, and just copy the `7` into +the existing memory. After updating `capacity` and `len`, it looks like this: + +```text +struct Vec { + data:
, + capacity: 4, + length: 4, +} +``` + +We can do even better than this, though. While `new` allocates a new empty +vector, we can use `with_capacity` if we know how many things we're going to +insert: + +```rust +let mut v = Vec::with_capacity(4); +# +# v.push(5); +# v.push(6); +# v.push(7); +# v.push(8); +``` + +Here, our initial vector looks like this: + +```text +struct Vec { + data: , + capacity: 4, + length: 0, +} +``` + +Now, when we do our `push`es, we won't need to allocate until we `push` our +fifth element. The `vec!` macro uses a similar trick, so don't worry about it! + +## Destroying a vector + +Like any other `struct`, a vector will be freed when it goes out of scope: + +```rust +{ + let v = vec![1, 2, 3, 4]; + + // do stuff with v + +} // <- v goes out of scope and is freed here +``` + +When the vector gets dropped, it will also drop all of its contents, so those +integers are going to be taken care of as well. This may seem like a +straightforward point now, but can get a little more complicated once we start +to introduce references to the elements of the vector. Let's tackle that next! + +## Reading elements of vectors + +Now that we know how to make vectors, knowing how to read their contents is a +good next step. There are two ways to reference a value stored in a vector. +We've added in the return types for extra clarity: + +```rust +let v = vec![1, 2, 3, 4, 5]; + +let three: &i32 = &v[2]; +let three: Option<&i32> = v.get(2); +``` + +First, note that we use `2` to get the third element: vectors are indexed by +number, starting at zero. Secondly, we have two different ways to do this: `&` +and `[]`s, and a method, `get`. The square brackets give us a reference, and +`get` gives us an `Option<&T>`. Why two ways? Well, what happens if we tried to +do this: + +```rust,should_panic +let v = vec![1, 2, 3, 4, 5]; + +let does_not_exist = &v[100]; +let does_not_exist = v.get(100); +``` + +With the `[]`s, Rust will cause a `panic!`. With the `get` method, it will +instead return `None`. But it's important to note that while `panic!`s will +cause your program to stop executing, they do not cause memory unsafety. + +The borrow checker remains vigilant about references to the contents of the +vector, and will make sure that everything stays valid. For example, here's +a case that looks okay, but actually isn't: + +```rust,ignore +let mut v = vec![1, 2, 3, 4, 5]; + +let first = &v[0]; + +v.push(6); +``` + +This will give us this error: + +```text +error: cannot borrow `v` as mutable because it is also borrowed as immutable [E0502] +v.push(6); +^ +note: immutable borrow occurs here +let first = &v[0]; + ^ +note: immutable borrow ends here +} +^ +error: aborting due to previous error(s) +``` + +What's the matter here? Remember what can happen when we `push` to a vector: it +might have to go get more memory, and copy all of the values to that new +memory. If it has to do this, our `first` would be pointing to old, invalid +memory! diff --git a/src/ch09-03-strings.md b/src/ch09-03-strings.md new file mode 100644 index 000000000..9acec32a8 --- /dev/null +++ b/src/ch09-03-strings.md @@ -0,0 +1,13 @@ +# Strings + +## creating + +new, push_str, String::from and .to_string() + +## reading + +## updating + +## implementaiton details + +just like vecs with extra utf8 checks diff --git a/src/ch09-04-hash-map.md b/src/ch09-04-hash-map.md new file mode 100644 index 000000000..56f0c96b9 --- /dev/null +++ b/src/ch09-04-hash-map.md @@ -0,0 +1,15 @@ +# `HashMap` + +## creating + +new, insert + +## reading + +## updating + +entry! + +## implementaiton details + +still growable, but doesn't work like vec does From d9591c1928c3ca1fc3bff6df122b38bf2afe31d7 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 21 Jul 2016 16:50:21 -0400 Subject: [PATCH 02/34] Small wording, punctuation, spelling edits --- src/ch09-01-basic-collections.md | 4 +-- src/ch09-02-vectors.md | 61 ++++++++++++++++---------------- 2 files changed, 33 insertions(+), 32 deletions(-) diff --git a/src/ch09-01-basic-collections.md b/src/ch09-01-basic-collections.md index c1fbff98f..81f307a03 100644 --- a/src/ch09-01-basic-collections.md +++ b/src/ch09-01-basic-collections.md @@ -3,7 +3,7 @@ Rust's standard library includes a number of really useful data structures called 'collections'. Most types represent one specific value, but collections can contain multiple values inside of them. Each collection has different -capabilities and costs, and chosing an appropriate one for the situation you're +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: @@ -13,4 +13,4 @@ collections which are used very often in Rust programs: * *HashMap*s allow you to associate a value with a particular key. There are more specialized variants of each of these data structures for -special situations, but these ones are the most fundamental. +special situations, but these are the most fundamental. diff --git a/src/ch09-02-vectors.md b/src/ch09-02-vectors.md index 3c2ce7d9c..b6b57abf3 100644 --- a/src/ch09-02-vectors.md +++ b/src/ch09-02-vectors.md @@ -1,7 +1,7 @@ # Vectors The first type we'll look at is `Vec`, also known as a 'vector'. Vectors -allow you to store more than one value in a single data structure, next to each +allow you to store more than one value in a single data structure next to each other in memory. ## Creating a new vector @@ -13,10 +13,10 @@ let v: Vec = Vec::new(); ``` You'll note that we added a type annotation here. Because we don't actually do -anything with the vector, Rust doesn't know what sort of elements we intend to -store. This is an important point. Vectors are homogenous; they may store many -values, but those values must be all of the same type. Vectors are generic over -the type you store inside them, so we use the angle brackets to tell Rust that +anything with the vector, Rust doesn't know what kind of elements we intend to +store. This is an important point. Vectors are homogenous: they may store many +values, but those values must all be the same type. Vectors are generic over +the type you store inside them, and the angle brackets here tell Rust that this vector will hold elements of the `i32` type. That said, in real code, you very rarely need to do this type annotation. Let's @@ -53,14 +53,14 @@ struct Vec { } ``` -This is not literally true, but will help you gain some intutions about it at -a high level. The actual representation is quite involved, and you can [read a -chapter in the Nomicon][nomicon] for the full details. +This is not literally true, but will help you gain some intutions about it. The +actual representation is quite involved, and you can [read a chapter in the +Nomicon][nomicon] for the full details. [nomicon]: https://doc.rust-lang.org/stable/nomicon/vec.html At a high level, though, this is okay: a vector has a reference to some data, -a capacity, and a length. Let's go through these lines of code, and see how +a capacity, and a length. Let's go through these lines of code and see how the vector changes. ```rust @@ -123,14 +123,13 @@ v.push(6); # v.push(8); ``` -Same thing, we `push` a `6`. And, in this case, the same thing will happen: +Same thing, we `push` a `6`. In this case, the same thing will happen: `push` looks at the values of `capacity` and `len`, and sees that we don't have room for a second element. So here's what it does: it requests room for twice as many elements as we currently have. In this case, that means two elements. -It then copies the existing element over into the new memory allocation, and -then copies the `6` into the next open slot. After updating the internal -values, it now looks like this: - +Once it gets the memory it requested, the code in `push` copies the existing +element over into the new memory allocation then copies the `6` into the next +open slot. After updating the internal values, the vector now looks like this: ```text struct Vec { @@ -141,7 +140,7 @@ struct Vec { ``` Our `capacity` and `length` both show two here. Let's try inserting another -elment into the vector: +element into the vector: ```rust # let mut v = Vec::new(); @@ -154,7 +153,7 @@ v.push(7); Same story here: `push` looks and sees that our vector is full. However, this time, something is slightly different. We currently have a capacity of -two elements. So the vector will request memory for double that number of +two elements, so the vector will request memory for double that number of elements from the operating system: four. But why does it double every time? We'll learn about that soon. For now, `push` will then copy the first two elements over to the new memory, copy our `7` onto the end, and then update @@ -170,11 +169,12 @@ struct Vec { Ah ha! A difference. In essence, `capacity` tracks how much memory we've got saved away for holding elements. `length` keeps track of how many elements we -are actually storing. Why not just allocate exactly how much we need? In order -to get more heap memory, we have to talk to the operating system, and that's -slower. Not only that, but we have to copy the contents of the vector from the -old memory to the new memory each time. So we make a tradeoff: we allocate a -bit more memory than we need, but in exchange, we get speed. +are actually storing. Why not just allocate exactly as much as we need? In order +to get more heap memory, we have to talk to the operating system, and that +takes time. Not only that, but each time we get chunk of memory, we have to +copy the contents of the vector from the old memory to the new memory. So we +make a tradeoff: we request a bit more memory than we need, but in exchange, +we speed up the next few `push` operations. We can see this speed the next time we call `push`: @@ -189,7 +189,7 @@ v.push(7); Now, `push` looks at the capacity versus the length: we have room for four elements, but we only have three elements. Perfect! We skip that "request more -memory from the OS and copy everything" business, and just copy the `7` into +memory from the OS and copy everything" business and just copy the `7` into the existing memory. After updating `capacity` and `len`, it looks like this: ```text @@ -248,7 +248,8 @@ to introduce references to the elements of the vector. Let's tackle that next! Now that we know how to make vectors, knowing how to read their contents is a good next step. There are two ways to reference a value stored in a vector. -We've added in the return types for extra clarity: +We've annotated the types of the values that are returned from these functions +for extra clarity: ```rust let v = vec![1, 2, 3, 4, 5]; @@ -258,10 +259,10 @@ let three: Option<&i32> = v.get(2); ``` First, note that we use `2` to get the third element: vectors are indexed by -number, starting at zero. Secondly, we have two different ways to do this: `&` -and `[]`s, and a method, `get`. The square brackets give us a reference, and -`get` gives us an `Option<&T>`. Why two ways? Well, what happens if we tried to -do this: +number, starting at zero. Secondly, we have two different ways to do this: +using `&` and `[]`s and using a method, `get()`. The square brackets give us a +reference, and `get()` gives us an `Option<&T>`. Why two ways? Well, what +happens if we tried to do this: ```rust,should_panic let v = vec![1, 2, 3, 4, 5]; @@ -271,11 +272,11 @@ let does_not_exist = v.get(100); ``` With the `[]`s, Rust will cause a `panic!`. With the `get` method, it will -instead return `None`. But it's important to note that while `panic!`s will +instead return `None` without `panic!`ing. Remember that while `panic!`s will cause your program to stop executing, they do not cause memory unsafety. The borrow checker remains vigilant about references to the contents of the -vector, and will make sure that everything stays valid. For example, here's +vector and will make sure that everything stays valid. For example, here's a case that looks okay, but actually isn't: ```rust,ignore @@ -302,6 +303,6 @@ error: aborting due to previous error(s) ``` What's the matter here? Remember what can happen when we `push` to a vector: it -might have to go get more memory, and copy all of the values to that new +might have to go get more memory and copy all of the values to that new memory. If it has to do this, our `first` would be pointing to old, invalid memory! From 57fd1a575c6c24094d6014b1687de4588473d3ea Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Fri, 26 Aug 2016 15:33:44 -0400 Subject: [PATCH 03/34] basic -> essential --- src/SUMMARY.md | 4 +++- ...-basic-collections.md => ch09-01-essential-collections.md} | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) rename src/{ch09-01-basic-collections.md => ch09-01-essential-collections.md} (97%) diff --git a/src/SUMMARY.md b/src/SUMMARY.md index fbe7d919e..47cc73add 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -31,7 +31,9 @@ - [Controlling visibility with `pub`](ch07-02-controlling-visibility-with-pub.md) - [Importing names with `use`](ch07-03-importing-names-with-use.md) -- [Basic Collections](ch09-01-basic-collections.md) +- [Error Handling]() + +- [Essential Collections](ch09-01-essential-collections.md) - [Vectors](ch09-02-vectors.md) - [Strings](ch09-03-strings.md) - [`HashMap`](ch09-04-hash-map.md) diff --git a/src/ch09-01-basic-collections.md b/src/ch09-01-essential-collections.md similarity index 97% rename from src/ch09-01-basic-collections.md rename to src/ch09-01-essential-collections.md index 81f307a03..896252a83 100644 --- a/src/ch09-01-basic-collections.md +++ b/src/ch09-01-essential-collections.md @@ -1,4 +1,4 @@ -# Basic Collections +# Essential Collections Rust's standard library includes a number of really useful data structures called 'collections'. Most types represent one specific value, but collections From a47516a1715b152412555f2f0d9e775019432e56 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Fri, 26 Aug 2016 15:48:56 -0400 Subject: [PATCH 04/34] remove the fun stuff --- src/ch09-02-vectors.md | 195 ++--------------------------------------- 1 file changed, 6 insertions(+), 189 deletions(-) diff --git a/src/ch09-02-vectors.md b/src/ch09-02-vectors.md index b6b57abf3..7c7bce95c 100644 --- a/src/ch09-02-vectors.md +++ b/src/ch09-02-vectors.md @@ -40,191 +40,8 @@ values like this is very common, and so there's a macro to do it for us: let v = vec![5, 6, 7, 8]; ``` -This macro does the exact same thing as our previous example, but it's much -more convenient. - -How does this all work? Under the hood, vectors look approximately like this: - -```rust,ignore -struct Vec { - data: &mut T, - capacity: usize, - length: usize, -} -``` - -This is not literally true, but will help you gain some intutions about it. The -actual representation is quite involved, and you can [read a chapter in the -Nomicon][nomicon] for the full details. - -[nomicon]: https://doc.rust-lang.org/stable/nomicon/vec.html - -At a high level, though, this is okay: a vector has a reference to some data, -a capacity, and a length. Let's go through these lines of code and see how -the vector changes. - -```rust -let mut v = Vec::new(); -# -# v.push(5); -# v.push(6); -# v.push(7); -# v.push(8); -``` - -We've created our new vector. It will look like this: - -```text -Vec { - data: , - capacity: 0, - length: 0, -} -``` - -We don't have anything stored yet, so the vector hasn't made any room for any -elements. Since we don't have any elements, `data` isn't valid either. - -```rust -# let mut v = Vec::new(); -# -v.push(5); -# v.push(6); -# v.push(7); -# v.push(8); -``` - -Next, we insert one value into the vector. `push` looks at the current capacity -and length, and sees that there's no room for this `5` to go. Since there's -currently room for zero elements, it will request enough memory from the -operating system for a single element, and then copy `5` into that memory. It -then updates the internal details, and now they look like this: - -```text -struct Vec { - data:
, - capacity: 1, - length: 1, -} -``` - -Our `data` now points to the start of this memory, and `capacity` and `length` -are both set to one. If they're both set to the same value, what's the -difference? We will see that shortly. But first, let's insert another value -into the vector: - - -```rust -# let mut v = Vec::new(); -# -# v.push(5); -v.push(6); -# v.push(7); -# v.push(8); -``` - -Same thing, we `push` a `6`. In this case, the same thing will happen: -`push` looks at the values of `capacity` and `len`, and sees that we don't have -room for a second element. So here's what it does: it requests room for twice -as many elements as we currently have. In this case, that means two elements. -Once it gets the memory it requested, the code in `push` copies the existing -element over into the new memory allocation then copies the `6` into the next -open slot. After updating the internal values, the vector now looks like this: - -```text -struct Vec { - data:
, - capacity: 2, - length: 2, -} -``` - -Our `capacity` and `length` both show two here. Let's try inserting another -element into the vector: - -```rust -# let mut v = Vec::new(); -# -# v.push(5); -# v.push(6); -v.push(7); -# v.push(8); -``` - -Same story here: `push` looks and sees that our vector is full. However, -this time, something is slightly different. We currently have a capacity of -two elements, so the vector will request memory for double that number of -elements from the operating system: four. But why does it double every time? -We'll learn about that soon. For now, `push` will then copy the first two -elements over to the new memory, copy our `7` onto the end, and then update -the internal state. What's it look like now? - -```text -struct Vec { - data:
, - capacity: 4, - length: 3, -} -``` - -Ah ha! A difference. In essence, `capacity` tracks how much memory we've got -saved away for holding elements. `length` keeps track of how many elements we -are actually storing. Why not just allocate exactly as much as we need? In order -to get more heap memory, we have to talk to the operating system, and that -takes time. Not only that, but each time we get chunk of memory, we have to -copy the contents of the vector from the old memory to the new memory. So we -make a tradeoff: we request a bit more memory than we need, but in exchange, -we speed up the next few `push` operations. - -We can see this speed the next time we call `push`: - -```rust -# let mut v = Vec::new(); -# -# v.push(5); -# v.push(6); -v.push(7); -# v.push(8); -``` - -Now, `push` looks at the capacity versus the length: we have room for four -elements, but we only have three elements. Perfect! We skip that "request more -memory from the OS and copy everything" business and just copy the `7` into -the existing memory. After updating `capacity` and `len`, it looks like this: - -```text -struct Vec { - data:
, - capacity: 4, - length: 4, -} -``` - -We can do even better than this, though. While `new` allocates a new empty -vector, we can use `with_capacity` if we know how many things we're going to -insert: - -```rust -let mut v = Vec::with_capacity(4); -# -# v.push(5); -# v.push(6); -# v.push(7); -# v.push(8); -``` - -Here, our initial vector looks like this: - -```text -struct Vec { - data: , - capacity: 4, - length: 0, -} -``` - -Now, when we do our `push`es, we won't need to allocate until we `push` our -fifth element. The `vec!` macro uses a similar trick, so don't worry about it! +This macro does a similar thing to our previous example, but it's much more +convenient. ## Destroying a vector @@ -302,7 +119,7 @@ note: immutable borrow ends here error: aborting due to previous error(s) ``` -What's the matter here? Remember what can happen when we `push` to a vector: it -might have to go get more memory and copy all of the values to that new -memory. If it has to do this, our `first` would be pointing to old, invalid -memory! +Why is this an error? Due to the way vectors work, adding a new element onto +the end might require allocating new memory and copying the old elements over. +If this happened, our reference would be pointing to deallocated memory. For +more on this, see the Nomicon: https://doc.rust-lang.org/stable/nomicon/vec.html From c9a21c8e5dafcc50f86993696cb5a6e830c1ba2c Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Fri, 26 Aug 2016 15:59:52 -0400 Subject: [PATCH 05/34] lol --- src/ch09-03-strings.md | 13 +++++++++---- src/ch09-04-hash-map.md | 3 --- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/ch09-03-strings.md b/src/ch09-03-strings.md index 9acec32a8..809284307 100644 --- a/src/ch09-03-strings.md +++ b/src/ch09-03-strings.md @@ -1,13 +1,18 @@ # Strings +We've already talked about strings a bunch in chapter four, but let's take a +more in-depth look at them now. + ## creating -new, push_str, String::from and .to_string() + + +new, String::from and .to_string() ## reading +slicing syntax, indexing + ## updating -## implementaiton details - -just like vecs with extra utf8 checks +push_str, concatenation diff --git a/src/ch09-04-hash-map.md b/src/ch09-04-hash-map.md index 56f0c96b9..dd988c636 100644 --- a/src/ch09-04-hash-map.md +++ b/src/ch09-04-hash-map.md @@ -10,6 +10,3 @@ new, insert entry! -## implementaiton details - -still growable, but doesn't work like vec does From 65691eeeed250ff7eb5556178db7f76c551fc81b Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Fri, 26 Aug 2016 17:02:53 -0400 Subject: [PATCH 06/34] start off the start of strings --- src/ch09-03-strings.md | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/ch09-03-strings.md b/src/ch09-03-strings.md index 809284307..7fafd0b1f 100644 --- a/src/ch09-03-strings.md +++ b/src/ch09-03-strings.md @@ -3,16 +3,27 @@ We've already talked about strings a bunch in chapter four, but let's take a more in-depth look at them now. -## creating +## Creating +You can create an empty string with `new`: +```rust +let s = String::new(); +``` -new, String::from and .to_string() +Often, you have some initial data that you'd like to start the string off with. +For that, there's the `.to_string()` method: -## reading +```rust +let data = "initial contents"; + +let s = data.to_string(); +``` + +## Reading slicing syntax, indexing -## updating +## Updating push_str, concatenation From c9044e9448dd8f9339a6a80514e7fa72f8dc7762 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Tue, 30 Aug 2016 15:13:11 -0400 Subject: [PATCH 07/34] strings --- src/ch09-03-strings.md | 282 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 279 insertions(+), 3 deletions(-) diff --git a/src/ch09-03-strings.md b/src/ch09-03-strings.md index 7fafd0b1f..9fb32af7c 100644 --- a/src/ch09-03-strings.md +++ b/src/ch09-03-strings.md @@ -3,6 +3,41 @@ We've already talked about strings a bunch in chapter four, but let's take a more in-depth look at them now. +## Six(?) kinds of strings + +Strings are a common place for new Rustaceans to get stuck. This is due to a +combination of three things: Rust's propensity for making sure to expose +possible errors, that strings are a more complicated data structure than many +programmers give them credit for, and UTF-8. These things combine in a way that +can seem difficult when you're used to other languages. + +Before we can dig into those things, we need to talk about what exactly we even +mean by the word 'string'. Rust-the-language has only one string type: `&str`. +We talked about these string slices in chapter four: they're a reference to some +UTF-8 encoded string data stored somewhere else. String literals, for example, +are stored in the binary output of your program, and are therefore string +slices. + +Rust's standard library also provides a type called `String`. This is a growable, +mutable, UTF-8 encoded string type. When Rustaceans talk about 'strings' in Rust, +they usually mean "`String` and `&str`." This chapter is largely about `String`, +and these two types are used heavily in Rust's standard library. This is what +Rustaceans mean when they say "Rust strings are UTF-8," since both `String` and +string slices are UTF-8 encoded. + +Rust's standard library also includes a number of other string types, such as +`OsString`, `OsStr`, `CString`, and `CStr`. Library crates may provide even +more options for string string data. As you can see from the `*String`/`*Str` +naming, they often provide an owned and borrowed variant, just like +`String`/`&str`. These string types may store different encodings, be +represented in memory in a different way, or all kinds of other things. We +won't be talking about them in this chapter, see their API documentation for +more about how to use them, and when each is appropriate. + +Many options! As I said, strings are surprisingly complex. Most of the time, +we'll be using `String` as an owned string type, though. So let's talk about +how to use it. + ## Creating You can create an empty string with `new`: @@ -18,12 +53,253 @@ For that, there's the `.to_string()` method: let data = "initial contents"; let s = data.to_string(); + +// the method also works on a literal directly: +let s = "initial contents".to_string(); ``` -## Reading +You'll also see this form sometimes: -slicing syntax, indexing +```rust +let s = String::from("Initial contents"); +``` + +Because strings are used for so many things, there are many different generic +APIs that make sense for strings. There are a lot of options, and some of them +can feel redundant because of this, but they all have their place! In this +case, `String::from` and `.to_string` end up doing the exact same thing, so +which you choose is a matter of style. Some people use `String::from` for +literals, and `.to_string` for variables bindings. Most Rust style is pretty +uniform, but this specific question is one of the most-debated. + +Don't forget that strings are UTF-8 encoded, and so you can include any +properly encoded data in them: + +```rust +let hello = "السلام عليكم"; +let hello = "Dobrý den"; +let hello = "Hello"; +let hello = "שָׁלוֹם"; +let hello = "नमस्ते"; +let hello = "こんにちは"; +let hello = "안녕하세요"; +let hello = "你好"; +let hello = "Olá"; +let hello = "Здравствуйте"; +let hello = "Hola"; +``` ## Updating -push_str, concatenation +You can grow a `String` by using the `push_str` method to append another +string: + +```rust +let mut s = String::from("foo"); + +s.push_str("bar"); + +// s will be "foobar" here +``` + +And `push` will add a `char`: + +```rust +let mut s = String::from("lo"); + +s.push('l'); + +// s will be "lol" here +``` + +You can make any string into the empty string with the `clear` method: + +```rust +let mut s = String::from("Noooooooooooooooooooooo!"); + +s.clear(); + +// s will be "" here +``` + +### Concatenation + +Often, you'll want to combine two strings together. One way is to use the `+` +operator: + +```rust +let s1 = String::from("Hello, "); +let s2 = String::from("world!"); + +let s3 = s1 + &s2; + +// s3 is "Hello, world!" +``` + +There's some tricky bits here, though! They come through the type signature +of `+` for strings. It looks something like this: + +```rust,ignore +fn add(self, s: &str) -> String { +``` + +I say 'something' because `add` is generic, and so this is what the signature +would be if it isn't. But this signature gives us all the clues we need about +the tricky bits of `+`. + +First of all, you'll notice that `s2` has an `&`. This is because of the `s` +argument in the function: you can only add a `&str` to a `String`, you can't +add two `String`s together. Remember back in chpater four when we talked about +how `&String` will coerce to `&str`? That's why it's `&s2`: so that it will +coerce to the proper type. + +Secondly, `add` takes ownership of `self`. This means that `s1` in the above +example will move. So while `let s3 = s1 + &s2;` looks like it will copy the +two strings and create a new one, it actually takes ownership of `s1`, appends +a copy of `s2`'s contents, and then returns ownership back. In other words, it +looks like it's making a lot of copies, but isn't. + +If you need to concatenate multiple strings, this behavior of `+` gets +unwieldy: + +```rust +let s1 = String::from("tic"); +let s2 = String::from("tac"); +let s3 = String::from("toe"); + +let s = s1 + "-" + &s2 + "-" + &s3; + +// s will be 'tic-tac-toe' here +``` + +With all of these `+`s and `"`s, it gets hard to see what's going on. For more +complicated string combining, we can use the `format!` macro: + +```rust +let s1 = String::from("tic"); +let s2 = String::from("tac"); +let s3 = String::from("toe"); + +let s = format!("{}-{}-{}", s1, s2, s3); + +// s will be 'tic-tac-toe' here +``` + +The `format!` macro works in the same way as `println!`, but instead of +printing the output to the screen, it returns a `String` with the contents. +This version is much easier to read than all of the `+`s. + +## Indexing strings + +If you try to access a string with the indexing syntax, you'll get an error. In +other words, this: + +```rust,ignore +let s1 = String::from("hello"); + +let h = s1[0]; +``` + +will give you this: + +```text +error: the trait bound `std::string::String: std::ops::Index<_>` is not satisfied [--explain E0277] + --> :4:14 + |> +4 |> let s3 = s1[0]; + |> ^^^^^ +note: the type `std::string::String` cannot be indexed by `_` +``` + +That note tells the story: Rust strings don't support indexing like this. So +the follow-up question is, why not? In order to answer that, we have to talk a +bit about how Rust stores strings in memory. + +### Internal representation + +A `String` is a wrapper over a `Vec`. Let's take a look at some of our +examples from before. First, this one: + +```rust +let len = "Hola".len(); +``` + +In this case, `len` will be four bytes long: each of these letters takes one +byte when encoded in UTF-8. What about this one, though? + +```rust +let len = "Здравствуйте".len(); +``` + +There are two answers that make sense here: the first is 12, which is the number +of letters that it would be if you asked someone. The second, though, is the +real answer here: 24. This is the number of bytes that it takes to encode +"Здравствуйте" in UTF-8: each character is two bytes. + +By the same token, imagine this invalid Rust code: + +```rust,ignore +let hello = "Здравствуйте"; + +let answer = &h[0]; +``` + +What should the value of `answer` be? Should it be `З`, the first letter? Or +should it be `208`? When you encode `З` in UTF-8, the first byte is `208`, and +the second is `151`. If it's `208`, well, that's not a valid character on its +own. So... do we make `[]` return an integer? For latin letters, this would +then not return the answer you'd expect: `&"hello"[0]` would then give `104`, +not `h`. + +This leads to another point about UTF-8: there are really three relevant ways +to look at strings, from Rust's perspective: bytes, scalar values, and grapheme +clusters. If we look at "नमस्ते ", it ultimately boils down to: + +```text +[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135, 32] +``` + +That's 19 bytes. But if you look at them as Unicode scalar values, which are what +Rust's `char` type is, those bytes look like this: + +```text +['न', 'म', 'स', '्', 'त', 'े', ' '] +``` + +There are seven of them, and the last one isn't even visible! Finally, if you +look at them as grapheme clusters, which is the closest thing to what humans +would call 'letters', you'd get this: + +```text +["न", "म", "स्", "ते", " "] +``` + +Five elemtns, and there's still that empty character on the end. It turns out +that even within 'grapheme cluster', there are multiple ways of grouping +things. Have we convinced you strings are actually really complicated yet? + +Furthermore, `[]` implies *O(n)* access time. But because UTF-8 is a +variable-length encoding, implementing `[]` on strings would be *O(n)* instead, +which would make it significantly worse-performing than what people expect. + +All of these problems means that we decided to not implement `[]` for strings, so +you cannot directly do this. + +However. + +Sometimes, indexing the bytes of a string is useful. So while you can't use `[]` +with a single number, you _can_ use `[]` with a range: + +```rust +let hello = "Здравствуйте"; + +let s = &hello[0..4]; +``` + +Here, `s` will be a `&str` that contains the first four bytes of the string. +Earlier, we mentioned that each of these characters was two bytes, so that means +that `s` will be 'Зд'. + +What would happen if we did `&hello[0..1]`? We said each of these characters +required two bytes. The answer: it will panic, in the same way that accessing +an invalid index in a vector does. From b1525a9077b0c361fa24550728a8a9db49f7f097 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Tue, 30 Aug 2016 15:31:42 -0400 Subject: [PATCH 08/34] hashmaps --- src/ch09-04-hash-map.md | 77 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 2 deletions(-) diff --git a/src/ch09-04-hash-map.md b/src/ch09-04-hash-map.md index dd988c636..60125857d 100644 --- a/src/ch09-04-hash-map.md +++ b/src/ch09-04-hash-map.md @@ -1,12 +1,85 @@ # `HashMap` +The last of our essential collections is the hashmap. A `HashMap` +stores a mapping of keys to values. 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: a "hash", a "map", an "object", a "hash table", +an "associative array"... so many names. + +We'll go over the basic API in this chapter, but there's many more goodies +hiding in there. As always, check the standard library docs for more fun +things to do with hashmaps. + ## creating -new, insert +We can create an empty hashmap with `new`, and add things with `insert`: + +```rust +use std::collections::HashMap; + +let mut map = HashMap::new(); + +map.insert(1, "hello"); +map.insert(2, "world"); +``` + +You'll note that we need to `use` the `HashMap` from the collections portion of +the standard library. Of our three essential collections, this one is the least +often used, and so 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, and so need +to be `use`d directly. ## reading +We can get a value out of the hashmap by providing the proper key to the `get` +method: + +```rust +use std::collections::HashMap; + +let mut map = HashMap::new(); + +map.insert(1, "hello"); +map.insert(2, "world"); + +let value = map.get(&2); +``` + +Here, `value` will have the value `Some("world")`, since that's the value +associated with the `2` key. It's wrapped in `Some` because `get` returns an +`Option`, that is, if there's no value for that key, it will return `None`. + ## updating -entry! +It's common to want to see if there's some sort of value already stored in the hashmap, +and if not, insert something. Hashmaps have a special API for this, called `entry`: +```rust +use std::collections::HashMap; + +let mut map = HashMap::new(); + +map.insert(1, "hello"); + +let e = map.entry(2); +``` + +Here, `e` is a special enum, `Entry`. An entry represents a value that might +exist, or might not. Let's say that we want to see if the key `2` has a value +associated with it. If it doesn't, we want to insert `"world"`, and then in +both cases, return the value. With the entry API, it looks like this: + +```rust +use std::collections::HashMap; + +let mut map = HashMap::new(); + +map.insert(1, "hello"); + +let e = map.entry(2).or_insert("world"); +``` + +The `or_insert` method on entry does exactly this: returns the value, and if +not, inserts its argument and returns that. This is much cleaner than writing +the logic yourself, and in addition, plays more nicely with the borrow checker. From 91396aa0e64b8094e9d9999961911af6a0306ed8 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Wed, 31 Aug 2016 13:38:19 -0400 Subject: [PATCH 09/34] add some more --- src/ch09-04-hash-map.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/ch09-04-hash-map.md b/src/ch09-04-hash-map.md index 60125857d..d339bb127 100644 --- a/src/ch09-04-hash-map.md +++ b/src/ch09-04-hash-map.md @@ -30,6 +30,18 @@ often used, and so 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, and so need to be `use`d directly. +Just like vectors, hashmaps store their data on the heap. + +If you have a vector of tuples, you can convert it into a hashmap with `collect`: + +```rust +use std::collections::HashMap; + +let data = vec![(1, "hello"), (2, "world")]; + +let map: HashMap = data.into_iter().collect(); +``` + ## reading We can get a value out of the hashmap by providing the proper key to the `get` @@ -50,6 +62,22 @@ Here, `value` will have the value `Some("world")`, since that's the value associated with the `2` key. It's wrapped in `Some` because `get` returns an `Option`, that is, if there's no value for that key, it will return `None`. +We can iterate over a hasmap in a similar manner as we do with vectors, using +a `for` loop: + +```rust +use std::collections::HashMap; + +let mut map = HashMap::new(); + +map.insert(1, "hello"); +map.insert(2, "world"); + +for (key, value) in &map { + println!("{}: {}", key, value); +} +``` + ## updating It's common to want to see if there's some sort of value already stored in the hashmap, From 2570566cb0c322238c46dca4073c53e58a8177fb Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 15 Sep 2016 16:12:29 -0400 Subject: [PATCH 10/34] Small wording edits --- src/ch09-01-essential-collections.md | 20 ++++++++++---------- src/ch09-02-vectors.md | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/ch09-01-essential-collections.md b/src/ch09-01-essential-collections.md index 896252a83..e9cb68573 100644 --- a/src/ch09-01-essential-collections.md +++ b/src/ch09-01-essential-collections.md @@ -1,16 +1,16 @@ # Essential Collections Rust's standard library includes a number of really useful data structures -called 'collections'. Most types represent one specific value, but collections -can contain multiple values inside of them. Each collection has 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: +called *collections*. Most other types represent one specific value, but +collections can contain multiple values inside of them. Each collection has +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: -* *Vector*s allow you to store a variable number of values next to each other. -* We've seen *String*s before, but we'll talk about them some more: they're - collections of characters. -* *HashMap*s allow you to associate a value with a particular key. +* A *Vector* allows you 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 you to associate a value with a particular key. There are more specialized variants of each of these data structures for -special situations, but these are the most fundamental. +particular situations, but these are the most fundamental and common. diff --git a/src/ch09-02-vectors.md b/src/ch09-02-vectors.md index 7c7bce95c..678ae3d1c 100644 --- a/src/ch09-02-vectors.md +++ b/src/ch09-02-vectors.md @@ -1,6 +1,6 @@ # Vectors -The first type we'll look at is `Vec`, also known as a 'vector'. Vectors +The first type we'll look at is `Vec`, also known as a *vector*. Vectors allow you to store more than one value in a single data structure next to each other in memory. From cd5517b8a0e143e4b3a031d5053f22c2f7eb36b2 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 15 Sep 2016 16:18:47 -0400 Subject: [PATCH 11/34] Remove double error handling from summary --- src/SUMMARY.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 47cc73add..8dbcace94 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -31,8 +31,6 @@ - [Controlling visibility with `pub`](ch07-02-controlling-visibility-with-pub.md) - [Importing names with `use`](ch07-03-importing-names-with-use.md) -- [Error Handling]() - - [Essential Collections](ch09-01-essential-collections.md) - [Vectors](ch09-02-vectors.md) - [Strings](ch09-03-strings.md) From f80bccaa64b16fb271b8f2c82f692e1da0580091 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 15 Sep 2016 16:21:27 -0400 Subject: [PATCH 12/34] Renaming files to match currently planned chapter order --- src/SUMMARY.md | 8 ++++---- ...al-collections.md => ch08-00-essential-collections.md} | 0 src/{ch09-02-vectors.md => ch08-01-vectors.md} | 0 src/{ch09-03-strings.md => ch08-02-strings.md} | 0 src/{ch09-04-hash-map.md => ch08-03-hash-map.md} | 0 5 files changed, 4 insertions(+), 4 deletions(-) rename src/{ch09-01-essential-collections.md => ch08-00-essential-collections.md} (100%) rename src/{ch09-02-vectors.md => ch08-01-vectors.md} (100%) rename src/{ch09-03-strings.md => ch08-02-strings.md} (100%) rename src/{ch09-04-hash-map.md => ch08-03-hash-map.md} (100%) diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 8dbcace94..7aff0fa83 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -31,10 +31,10 @@ - [Controlling visibility with `pub`](ch07-02-controlling-visibility-with-pub.md) - [Importing names with `use`](ch07-03-importing-names-with-use.md) -- [Essential Collections](ch09-01-essential-collections.md) - - [Vectors](ch09-02-vectors.md) - - [Strings](ch09-03-strings.md) - - [`HashMap`](ch09-04-hash-map.md) +- [Essential Collections](ch08-00-essential-collections.md) + - [Vectors](ch08-01-vectors.md) + - [Strings](ch08-02-strings.md) + - [`HashMap`](ch08-03-hash-map.md) - [Error Handling]() diff --git a/src/ch09-01-essential-collections.md b/src/ch08-00-essential-collections.md similarity index 100% rename from src/ch09-01-essential-collections.md rename to src/ch08-00-essential-collections.md diff --git a/src/ch09-02-vectors.md b/src/ch08-01-vectors.md similarity index 100% rename from src/ch09-02-vectors.md rename to src/ch08-01-vectors.md diff --git a/src/ch09-03-strings.md b/src/ch08-02-strings.md similarity index 100% rename from src/ch09-03-strings.md rename to src/ch08-02-strings.md diff --git a/src/ch09-04-hash-map.md b/src/ch08-03-hash-map.md similarity index 100% rename from src/ch09-04-hash-map.md rename to src/ch08-03-hash-map.md From a417244d981fd9741b6b536f64ec0c5056fae681 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 15 Sep 2016 18:14:02 -0400 Subject: [PATCH 13/34] Edits to Vec - be more specific, update error messages --- src/ch08-01-vectors.md | 112 ++++++++++++++++++++++++----------------- 1 file changed, 67 insertions(+), 45 deletions(-) diff --git a/src/ch08-01-vectors.md b/src/ch08-01-vectors.md index 678ae3d1c..9bf4e328e 100644 --- a/src/ch08-01-vectors.md +++ b/src/ch08-01-vectors.md @@ -1,8 +1,8 @@ # Vectors The first type we'll look at is `Vec`, also known as a *vector*. Vectors -allow you to store more than one value in a single data structure next to each -other in memory. +allow you to store more than one value in a single data structure that puts all +the values next to each other in memory. ## Creating a new vector @@ -16,12 +16,13 @@ You'll note that we added a type annotation here. Because we don't actually do anything with the vector, Rust doesn't know what kind of elements we intend to store. This is an important point. Vectors are homogenous: they may store many values, but those values must all be the same type. Vectors are generic over -the type you store inside them, and the angle brackets here tell Rust that -this vector will hold elements of the `i32` type. +the type you store inside them (we'll talk about Generics more throroughly in +Chapter XX), and the angle brackets here tell Rust that this vector will hold +elements of the `i32` type. -That said, in real code, you very rarely need to do this type annotation. Let's -insert some values to see this in action. To put elements in the vector, we can -use the `push` method: +That said, in real code, you very rarely need to do this type annotation since +Rust can infer the type of value we want to store once we insert values. Let's +see this in action. To put elements in the vector, we can use the `push` method: ```rust let mut v = Vec::new(); @@ -32,9 +33,11 @@ v.push(7); v.push(8); ``` -Since these numbers are `i32`s, Rust can infer the type of the vector, so we -don't need the annotation. That said, creating a vector with some initial -values like this is very common, and so there's a macro to do it for us: +Since these numbers are `i32`s, Rust infers the type of data we want to store +in the vector, so we don't need the `` annotation. + +We can improve this code even further. Creating a vector with some initial +values like this is very common, so there's a macro to do it for us: ```rust let v = vec![5, 6, 7, 8]; @@ -57,29 +60,32 @@ Like any other `struct`, a vector will be freed when it goes out of scope: ``` When the vector gets dropped, it will also drop all of its contents, so those -integers are going to be taken care of as well. This may seem like a -straightforward point now, but can get a little more complicated once we start -to introduce references to the elements of the vector. Let's tackle that next! +integers are going to be cleaned up as well. This may seem like a +straightforward point, but can get a little more complicated once we start to +introduce references to the elements of the vector. Let's tackle that next! ## Reading elements of vectors -Now that we know how to make vectors, knowing how to read their contents is a -good next step. There are two ways to reference a value stored in a vector. -We've annotated the types of the values that are returned from these functions -for extra clarity: +Now that we know how creating and destroying vectors works, knowing how to read +their contents is a good next step. There are two ways to reference a value +stored in a vector. In the following examples of these two ways, we've +annotated the types of the values that are returned from these functions for +extra clarity: ```rust let v = vec![1, 2, 3, 4, 5]; -let three: &i32 = &v[2]; -let three: Option<&i32> = v.get(2); +let third: &i32 = &v[2]; +let third: Option<&i32> = v.get(2); ``` -First, note that we use `2` to get the third element: vectors are indexed by -number, starting at zero. Secondly, we have two different ways to do this: -using `&` and `[]`s and using a method, `get()`. The square brackets give us a -reference, and `get()` gives us an `Option<&T>`. Why two ways? Well, what -happens if we tried to do this: +First, note that we use the index value of `2` to get the third element: +vectors are indexed by number, starting at zero. Secondly, the two different +ways to get the third element are using `&` and `[]`s and using the `get` +method. The square brackets give us a reference, and `get` gives us an +`Option<&T>`. The reason we have two ways to reference an element is so that we +can choose the behavior we'd like to have if we try to use an index value that +the vector doesn't have an element for: ```rust,should_panic let v = vec![1, 2, 3, 4, 5]; @@ -89,12 +95,17 @@ let does_not_exist = v.get(100); ``` With the `[]`s, Rust will cause a `panic!`. With the `get` method, it will -instead return `None` without `panic!`ing. Remember that while `panic!`s will -cause your program to stop executing, they do not cause memory unsafety. +instead return `None` without `panic!`ing. Deciding which way to access +elements in a vector depends on whether you consider an attempted access past +the end of the vector to be an error, in which case you would want the `panic!` +behavior, or whether this will happen occasionally under normal circumstances +and your code will have logic to handle getting `Some(&element)` or `None`. -The borrow checker remains vigilant about references to the contents of the -vector and will make sure that everything stays valid. For example, here's -a case that looks okay, but actually isn't: +Once we have a valid reference, the borrow checker will enforce the ownership +and borrowing rules we covered in Chapter 4 in order to ensure this and other +references to the contents of the vector stay valid. For example, here's code +that looks like it should be allowed, but it won't compile because the +references actually aren't valid anymore: ```rust,ignore let mut v = vec![1, 2, 3, 4, 5]; @@ -104,22 +115,33 @@ let first = &v[0]; v.push(6); ``` -This will give us this error: +Compiling this will give us this error: -```text -error: cannot borrow `v` as mutable because it is also borrowed as immutable [E0502] -v.push(6); -^ -note: immutable borrow occurs here -let first = &v[0]; - ^ -note: immutable borrow ends here -} -^ -error: aborting due to previous error(s) +```bash +error: cannot borrow `v` as mutable because it is also borrowed as immutable +[--explain E0502] + |> +5 |> let first = &v[0]; + |> - immutable borrow occurs here +7 |> v.push(6); + |> ^ mutable borrow occurs here +9 |> } + |> - immutable borrow ends here ``` -Why is this an error? Due to the way vectors work, adding a new element onto -the end might require allocating new memory and copying the old elements over. -If this happened, our reference would be pointing to deallocated memory. For -more on this, see the Nomicon: https://doc.rust-lang.org/stable/nomicon/vec.html +This violates one of the ownership rules we covered in Chapter 4: the `push` +method needs to have a mutable borrow to the `Vec`, and we aren't allowed to +have any immutable borrows while we have a mutable borrow. + +Why is it an error to have a reference to the first element in a vector while +we try to add a new item to the end, though? Due to the way vectors work, +adding a new element onto the end might require allocating new memory and +copying the old elements over to the new space if there wasn't enough room to +put all the elements next to each other where the vector was. If this happened, +our reference would be pointing to deallocated memory. For more on this, see +[The Nomicon](https://doc.rust-lang.org/stable/nomicon/vec.html). + +Be sure to take a look at the API documentation for all the methods defined on +`Vec` by the standard library. For example, in addition to `push` there's a +`pop` method that will remove and return the last element. Let's move on to the +next collection type: `String`! From 8f1b9229452d6135b1b96ffd2926f31b9185e629 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Fri, 16 Sep 2016 13:28:31 -0400 Subject: [PATCH 14/34] Make headings consistent with each other And title cased, and more descriptive --- src/ch08-00-essential-collections.md | 4 +++- src/ch08-01-vectors.md | 12 ++++++++---- src/ch08-02-strings.md | 14 +++++++------- src/ch08-03-hash-map.md | 8 ++++---- 4 files changed, 22 insertions(+), 16 deletions(-) diff --git a/src/ch08-00-essential-collections.md b/src/ch08-00-essential-collections.md index e9cb68573..7eea35bd3 100644 --- a/src/ch08-00-essential-collections.md +++ b/src/ch08-00-essential-collections.md @@ -13,4 +13,6 @@ go over three collections which are used very often in Rust programs: * A *HashMap* allows you 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. +particular situations, but these are the most fundamental and common. We're +going to discuss how to create and update each of the collections, as well as +what makes each special. diff --git a/src/ch08-01-vectors.md b/src/ch08-01-vectors.md index 9bf4e328e..5e15885f9 100644 --- a/src/ch08-01-vectors.md +++ b/src/ch08-01-vectors.md @@ -4,7 +4,7 @@ The first type we'll look at is `Vec`, also known as a *vector*. Vectors allow you to store more than one value in a single data structure that puts all the values next to each other in memory. -## Creating a new vector +## Creating a New Vector To create a new vector, you can call the `new` function: @@ -22,7 +22,11 @@ elements of the `i32` type. That said, in real code, you very rarely need to do this type annotation since Rust can infer the type of value we want to store once we insert values. Let's -see this in action. To put elements in the vector, we can use the `push` method: +look at how to modify a vector next. + +## Updating a Vector + +To put elements in the vector, we can use the `push` method: ```rust let mut v = Vec::new(); @@ -46,7 +50,7 @@ let v = vec![5, 6, 7, 8]; This macro does a similar thing to our previous example, but it's much more convenient. -## Destroying a vector +## Dropping a Vector Drops its Elements Like any other `struct`, a vector will be freed when it goes out of scope: @@ -64,7 +68,7 @@ integers are going to be cleaned up as well. This may seem like a straightforward point, but can get a little more complicated once we start to introduce references to the elements of the vector. Let's tackle that next! -## Reading elements of vectors +## Reading Elements of Vectors Now that we know how creating and destroying vectors works, knowing how to read their contents is a good next step. There are two ways to reference a value diff --git a/src/ch08-02-strings.md b/src/ch08-02-strings.md index 9fb32af7c..ad61b6891 100644 --- a/src/ch08-02-strings.md +++ b/src/ch08-02-strings.md @@ -3,7 +3,7 @@ We've already talked about strings a bunch in chapter four, but let's take a more in-depth look at them now. -## Six(?) kinds of strings +## Many Kinds of Strings Strings are a common place for new Rustaceans to get stuck. This is due to a combination of three things: Rust's propensity for making sure to expose @@ -37,10 +37,10 @@ more about how to use them, and when each is appropriate. Many options! As I said, strings are surprisingly complex. Most of the time, we'll be using `String` as an owned string type, though. So let's talk about how to use it. +## Creating a New String -## Creating - -You can create an empty string with `new`: +Let's look at how to do the same operations on `String` as we did with `Vec`, +starting with creating one. Similarly, `String` has `new`: ```rust let s = String::new(); @@ -89,7 +89,7 @@ let hello = "Здравствуйте"; let hello = "Hola"; ``` -## Updating +## Updating a String You can grow a `String` by using the `push_str` method to append another string: @@ -189,7 +189,7 @@ The `format!` macro works in the same way as `println!`, but instead of printing the output to the screen, it returns a `String` with the contents. This version is much easier to read than all of the `+`s. -## Indexing strings +## Indexing Strings If you try to access a string with the indexing syntax, you'll get an error. In other words, this: @@ -215,7 +215,7 @@ That note tells the story: Rust strings don't support indexing like this. So the follow-up question is, why not? In order to answer that, we have to talk a bit about how Rust stores strings in memory. -### Internal representation +### Internal Representation A `String` is a wrapper over a `Vec`. Let's take a look at some of our examples from before. First, this one: diff --git a/src/ch08-03-hash-map.md b/src/ch08-03-hash-map.md index d339bb127..4abad6287 100644 --- a/src/ch08-03-hash-map.md +++ b/src/ch08-03-hash-map.md @@ -1,4 +1,4 @@ -# `HashMap` +# HashMaps The last of our essential collections is the hashmap. A `HashMap` stores a mapping of keys to values. It does this via a "hashing function", @@ -11,7 +11,7 @@ We'll go over the basic API in this chapter, but there's many more goodies hiding in there. As always, check the standard library docs for more fun things to do with hashmaps. -## creating +## Creating a HashMap We can create an empty hashmap with `new`, and add things with `insert`: @@ -42,7 +42,7 @@ let data = vec![(1, "hello"), (2, "world")]; let map: HashMap = data.into_iter().collect(); ``` -## reading +## Accessing Values in a HashMap We can get a value out of the hashmap by providing the proper key to the `get` method: @@ -78,7 +78,7 @@ for (key, value) in &map { } ``` -## updating +## Updating a HashMap It's common to want to see if there's some sort of value already stored in the hashmap, and if not, insert something. Hashmaps have a special API for this, called `entry`: From 854614fc291ae86347aa52e952c5cd2c80e11c37 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Fri, 16 Sep 2016 13:31:45 -0400 Subject: [PATCH 15/34] Wording edits for strings --- src/ch08-02-strings.md | 186 ++++++++++++++++++++--------------------- 1 file changed, 91 insertions(+), 95 deletions(-) diff --git a/src/ch08-02-strings.md b/src/ch08-02-strings.md index ad61b6891..8bbe480de 100644 --- a/src/ch08-02-strings.md +++ b/src/ch08-02-strings.md @@ -1,42 +1,38 @@ # Strings -We've already talked about strings a bunch in chapter four, but let's take a -more in-depth look at them now. +We've already talked about strings a bunch in Chapter 4, but let's take a more +in-depth look at them now. ## Many Kinds of Strings Strings are a common place for new Rustaceans to get stuck. This is due to a combination of three things: Rust's propensity for making sure to expose -possible errors, that strings are a more complicated data structure than many +possible errors, strings being a more complicated data structure than many programmers give them credit for, and UTF-8. These things combine in a way that can seem difficult when you're used to other languages. Before we can dig into those things, we need to talk about what exactly we even mean by the word 'string'. Rust-the-language has only one string type: `&str`. -We talked about these string slices in chapter four: they're a reference to some +We talked about these string slices in Chapter 4: they're a reference to some UTF-8 encoded string data stored somewhere else. String literals, for example, are stored in the binary output of your program, and are therefore string slices. -Rust's standard library also provides a type called `String`. This is a growable, -mutable, UTF-8 encoded string type. When Rustaceans talk about 'strings' in Rust, -they usually mean "`String` and `&str`." This chapter is largely about `String`, -and these two types are used heavily in Rust's standard library. This is what -Rustaceans mean when they say "Rust strings are UTF-8," since both `String` and -string slices are UTF-8 encoded. +Rust's standard library also provides a type called `String`. This is a +growable, mutable, owned, UTF-8 encoded string type. When Rustaceans talk about +'strings' in Rust, they usually mean "`String` and `&str`". This chapter is +largely about `String`, and these two types are used heavily in Rust's standard +library. Both `String` and string slices are UTF-8 encoded. Rust's standard library also includes a number of other string types, such as `OsString`, `OsStr`, `CString`, and `CStr`. Library crates may provide even -more options for string string data. As you can see from the `*String`/`*Str` +more options for storing string data. As you can see from the `*String`/`*Str` naming, they often provide an owned and borrowed variant, just like -`String`/`&str`. These string types may store different encodings, be -represented in memory in a different way, or all kinds of other things. We -won't be talking about them in this chapter, see their API documentation for -more about how to use them, and when each is appropriate. +`String`/`&str`. These string types may store different encodings or be +represented in memory in a different way, for example. We won't be talking +about these other string types in this chapter; see their API documentation for +more about how to use them and when each is appropriate. -Many options! As I said, strings are surprisingly complex. Most of the time, -we'll be using `String` as an owned string type, though. So let's talk about -how to use it. ## Creating a New String Let's look at how to do the same operations on `String` as we did with `Vec`, @@ -69,10 +65,10 @@ APIs that make sense for strings. There are a lot of options, and some of them can feel redundant because of this, but they all have their place! In this case, `String::from` and `.to_string` end up doing the exact same thing, so which you choose is a matter of style. Some people use `String::from` for -literals, and `.to_string` for variables bindings. Most Rust style is pretty -uniform, but this specific question is one of the most-debated. +literals, and `.to_string` for variable bindings. Most Rust style is pretty +uniform, but this specific question is one of the most debated. -Don't forget that strings are UTF-8 encoded, and so you can include any +Don't forget that strings are UTF-8 encoded, so you can include any properly encoded data in them: ```rust @@ -91,37 +87,38 @@ let hello = "Hola"; ## Updating a String +A `String` can be changed and can grow in size, just like a `Vec` can. + +### Push + You can grow a `String` by using the `push_str` method to append another string: ```rust let mut s = String::from("foo"); - s.push_str("bar"); - -// s will be "foobar" here ``` -And `push` will add a `char`: +`s` will contain "foobar" after these two lines. + +The `push` method will add a `char`: ```rust let mut s = String::from("lo"); - s.push('l'); - -// s will be "lol" here ``` -You can make any string into the empty string with the `clear` method: +`s` will contain "lol" after this point. + +You can make any `String` contain the empty string with the `clear` method: ```rust let mut s = String::from("Noooooooooooooooooooooo!"); - s.clear(); - -// s will be "" here ``` +Now `s` will be the empty string, "". + ### Concatenation Often, you'll want to combine two strings together. One way is to use the `+` @@ -130,34 +127,37 @@ operator: ```rust let s1 = String::from("Hello, "); let s2 = String::from("world!"); - let s3 = s1 + &s2; - -// s3 is "Hello, world!" ``` -There's some tricky bits here, though! They come through the type signature -of `+` for strings. It looks something like this: +This code will make `s3` contain "Hello, world!" There's some tricky bits here, +though, that come from the type signature of `+` for `String`. The signature +for the `add` method that the `+` operator uses looks something like this: ```rust,ignore fn add(self, s: &str) -> String { ``` -I say 'something' because `add` is generic, and so this is what the signature -would be if it isn't. But this signature gives us all the clues we need about -the tricky bits of `+`. +This isn't excatly what the actual signature is in the standard library because +`add` is defined using generics there. Here, we're just looking at what the +signature of the method would be if `add` was defined specifically for +`String`. This signature gives us the clues we need in order to understand the +tricky bits of `+`. First of all, you'll notice that `s2` has an `&`. This is because of the `s` -argument in the function: you can only add a `&str` to a `String`, you can't -add two `String`s together. Remember back in chpater four when we talked about -how `&String` will coerce to `&str`? That's why it's `&s2`: so that it will -coerce to the proper type. +argument in the `add` function: you can only add a `&str` to a `String`, you +can't add two `String`s together. Remember back in Chapter 4 when we talked +about how `&String` will coerce to `&str`: we write `&s2` so that the `String` +will coerce to the proper type, `&str`. -Secondly, `add` takes ownership of `self`. This means that `s1` in the above -example will move. So while `let s3 = s1 + &s2;` looks like it will copy the -two strings and create a new one, it actually takes ownership of `s1`, appends -a copy of `s2`'s contents, and then returns ownership back. In other words, it -looks like it's making a lot of copies, but isn't. +Secondly, `add` takes ownership of `self`, which we can tell because `self` +does *not* have an `&` in the signature. This means `s1` in the above example +will be moved into the `add` call and no longer be a valid binding after that. +So while `let s3 = s1 + &s2;` looks like it will copy both strings and create a +new one, this statement actually takes ownership of `s1`, appends a copy of +`s2`'s contents, then returns ownership of the result. In other words, it looks +like it's making a lot of copies, but isn't: the implementation is more +efficient than copying. If you need to concatenate multiple strings, this behavior of `+` gets unwieldy: @@ -168,12 +168,11 @@ let s2 = String::from("tac"); let s3 = String::from("toe"); let s = s1 + "-" + &s2 + "-" + &s3; - -// s will be 'tic-tac-toe' here ``` -With all of these `+`s and `"`s, it gets hard to see what's going on. For more -complicated string combining, we can use the `format!` macro: +`s` will be "tic-tac-toe" at this point. With all of the `+` and `"` +characters, it gets hard to see what's going on. For more complicated string +combining, we can use the `format!` macro: ```rust let s1 = String::from("tic"); @@ -181,109 +180,106 @@ let s2 = String::from("tac"); let s3 = String::from("toe"); let s = format!("{}-{}-{}", s1, s2, s3); - -// s will be 'tic-tac-toe' here ``` -The `format!` macro works in the same way as `println!`, but instead of -printing the output to the screen, it returns a `String` with the contents. -This version is much easier to read than all of the `+`s. +This code will also set `s` to "tic-tac-toe". The `format!` macro works in the +same way as `println!`, but instead of printing the output to the screen, it +returns a `String` with the contents. This version is much easier to read than +all of the `+`s. -## Indexing Strings +## Indexing into Strings -If you try to access a string with the indexing syntax, you'll get an error. In -other words, this: +In many other languages, accessing individual characters in a string by +referencing the characters by index is a valid and common operation. In Rust, +however, if we try to access parts of a `String` using indexing syntax, we'll +get an error. That is, this code: ```rust,ignore let s1 = String::from("hello"); - let h = s1[0]; ``` -will give you this: +will result in this error: ```text -error: the trait bound `std::string::String: std::ops::Index<_>` is not satisfied [--explain E0277] - --> :4:14 +error: the trait bound `std::string::String: std::ops::Index<_>` is not +satisfied [--explain E0277] |> -4 |> let s3 = s1[0]; - |> ^^^^^ + |> let h = s1[0]; + |> ^^^^^ note: the type `std::string::String` cannot be indexed by `_` ``` -That note tells the story: Rust strings don't support indexing like this. So +The error and the note tell the story: Rust strings don't support indexing. So the follow-up question is, why not? In order to answer that, we have to talk a bit about how Rust stores strings in memory. ### Internal Representation A `String` is a wrapper over a `Vec`. Let's take a look at some of our -examples from before. First, this one: +properly-encoded UTF-8 example strings from before. First, this one: ```rust let len = "Hola".len(); ``` -In this case, `len` will be four bytes long: each of these letters takes one -byte when encoded in UTF-8. What about this one, though? +In this case, `len` will be four, which means the `Vec` storing the string +"Hola" is four bytes long: each of these letters takes one byte when encoded in +UTF-8. What about this example, though? ```rust let len = "Здравствуйте".len(); ``` -There are two answers that make sense here: the first is 12, which is the number -of letters that it would be if you asked someone. The second, though, is the -real answer here: 24. This is the number of bytes that it takes to encode -"Здравствуйте" in UTF-8: each character is two bytes. +There are two answers that potentially make sense here: the first is 12, which +is the number of letters that a person would count if we asked someone how long +this string was. The second, though, is what Rust's answer is: 24. This is the +number of bytes that it takes to encode "Здравствуйте" in UTF-8, because each +character takes two bytes of storage. By the same token, imagine this invalid Rust code: ```rust,ignore let hello = "Здравствуйте"; - let answer = &h[0]; ``` -What should the value of `answer` be? Should it be `З`, the first letter? Or -should it be `208`? When you encode `З` in UTF-8, the first byte is `208`, and -the second is `151`. If it's `208`, well, that's not a valid character on its -own. So... do we make `[]` return an integer? For latin letters, this would -then not return the answer you'd expect: `&"hello"[0]` would then give `104`, -not `h`. +What should the value of `answer` be? Should it be `З`, the first letter? When +you encode `З` in UTF-8, the first byte is `208`, and the second is `151`. So +should `answer` be `208`? `208` is not a valid character on its own, though. +Plus, for latin letters, this would not return the answer most people would +expect: `&"hello"[0]` would then return `104`, not `h`. This leads to another point about UTF-8: there are really three relevant ways to look at strings, from Rust's perspective: bytes, scalar values, and grapheme -clusters. If we look at "नमस्ते ", it ultimately boils down to: +clusters. If we look at the string "नमस्ते ", it is ultimately stored as a `Vec` +of `u8` values that looks like this: ```text [224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135, 32] ``` -That's 19 bytes. But if you look at them as Unicode scalar values, which are what -Rust's `char` type is, those bytes look like this: +That's 19 bytes. But if we look at them as Unicode scalar values, which are +what Rust's `char` type is, those bytes look like this: ```text ['न', 'म', 'स', '्', 'त', 'े', ' '] ``` -There are seven of them, and the last one isn't even visible! Finally, if you -look at them as grapheme clusters, which is the closest thing to what humans -would call 'letters', you'd get this: +There are seven `char` values here, and the last one isn't even visible! +Finally, if we look at them as grapheme clusters, which is the closest thing +to what humans would call 'letters', we'd get this: ```text ["न", "म", "स्", "ते", " "] ``` -Five elemtns, and there's still that empty character on the end. It turns out +Five elements, and there's still that empty character on the end. It turns out that even within 'grapheme cluster', there are multiple ways of grouping things. Have we convinced you strings are actually really complicated yet? -Furthermore, `[]` implies *O(n)* access time. But because UTF-8 is a -variable-length encoding, implementing `[]` on strings would be *O(n)* instead, -which would make it significantly worse-performing than what people expect. - -All of these problems means that we decided to not implement `[]` for strings, so -you cannot directly do this. +All of these problems mean that Rust does not implement `[]` for `String`, so +we cannot directly do this. However. From 1da1e810d2c113e1f4bd5d80c72474f4181e1ffc Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 19 Sep 2016 11:03:55 -0400 Subject: [PATCH 16/34] I'd rather explain _ than 'static at this point tbh --- src/ch08-03-hash-map.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/ch08-03-hash-map.md b/src/ch08-03-hash-map.md index 4abad6287..f3ed14d82 100644 --- a/src/ch08-03-hash-map.md +++ b/src/ch08-03-hash-map.md @@ -39,9 +39,15 @@ use std::collections::HashMap; let data = vec![(1, "hello"), (2, "world")]; -let map: HashMap = data.into_iter().collect(); +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 +types of the data in our vector. + ## Accessing Values in a HashMap We can get a value out of the hashmap by providing the proper key to the `get` From 99fc51d8481e8d88dbaae479499ef28129910f5f Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 19 Sep 2016 11:05:32 -0400 Subject: [PATCH 17/34] Edits and additions to HashMap --- src/ch08-03-hash-map.md | 173 ++++++++++++++++++++++++++++++++-------- 1 file changed, 140 insertions(+), 33 deletions(-) diff --git a/src/ch08-03-hash-map.md b/src/ch08-03-hash-map.md index f3ed14d82..78aaad3f7 100644 --- a/src/ch08-03-hash-map.md +++ b/src/ch08-03-hash-map.md @@ -1,19 +1,19 @@ # HashMaps -The last of our essential collections is the hashmap. A `HashMap` -stores a mapping of keys to values. 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: a "hash", a "map", an "object", a "hash table", -an "associative array"... so many names. +The last of our essential collections is the *HashMap*. A `HashMap` +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's many more goodies -hiding in there. As always, check the standard library docs for more fun -things to do with hashmaps. +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, +check the standard library documentation for more information. ## Creating a HashMap -We can create an empty hashmap with `new`, and add things with `insert`: +We can create an empty HashMap with `new`, and add elements with `insert`: ```rust use std::collections::HashMap; @@ -24,15 +24,20 @@ map.insert(1, "hello"); map.insert(2, "world"); ``` -You'll note that we need to `use` the `HashMap` from the collections portion of -the standard library. Of our three essential collections, this one is the least -often used, and so 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, and so need -to be `use`d directly. +Note that we need to `use` the `HashMap` from the collections portion of the +standard library. Of our three essential collections, this one is the least +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. +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. -If you have a vector of tuples, you can convert it into a hashmap with `collect`: +If you have a vector of tuples, you can convert it into a HashMap with the +`collect` method. The first element in each tuple will be the key, and the +second element will be the value: ```rust use std::collections::HashMap; @@ -48,10 +53,32 @@ 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 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: + +```rust +use std::collections::HashMap; + +let field_name = String::from("Favorite color"); +let field_value = String::from("Blue"); + +let mut map = HashMap::new(); +map.insert(field_name, field_value); +// field_name and field_value are invalid at this point +``` + +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`. + +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 +in the Lifetimes section of Chapter XX. + ## Accessing Values in a HashMap -We can get a value out of the hashmap by providing the proper key to the `get` -method: +We can get a value out of the HashMap by providing its key to the `get` method: ```rust use std::collections::HashMap; @@ -65,11 +92,12 @@ let value = map.get(&2); ``` Here, `value` will have the value `Some("world")`, since that's the value -associated with the `2` key. It's wrapped in `Some` because `get` returns an -`Option`, that is, if there's no value for that key, it will return `None`. +associated with the `2` key. "world" is wrapped in `Some` because `get` returns +an `Option`. If there's no value for that key in the HashMap, `get` will +return `None`. -We can iterate over a hasmap in a similar manner as we do with vectors, using -a `for` loop: +We can iterate over each key/value pair in a HashMap in a similar manner as we +do with vectors, using a `for` loop: ```rust use std::collections::HashMap; @@ -84,25 +112,53 @@ for (key, value) in &map { } ``` +This will print: + +```bash +1: hello +2: world +``` + ## Updating a HashMap -It's common to want to see if there's some sort of value already stored in the hashmap, -and if not, insert something. Hashmaps have a special API for this, called `entry`: +### Overwriting a Value + +If you 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: ```rust use std::collections::HashMap; let mut map = HashMap::new(); +map.insert(1, "hello"); +map.insert(1, "Hi There"); + +println!("{:?}", map); +``` + +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 +special API for this, called `entry`, that takes the key we want to check as an +argument: + +```rust +use std::collections::HashMap; + +let mut map = HashMap::new(); map.insert(1, "hello"); let e = map.entry(2); ``` -Here, `e` is a special enum, `Entry`. An entry represents a value that might -exist, or might not. Let's say that we want to see if the key `2` has a value -associated with it. If it doesn't, we want to insert `"world"`, and then in -both cases, return the value. With the entry API, it looks like this: +Here, the value bound to `e` is a special enum, `Entry`. An `Entry` represents a +value that might or might not exist. Let's say that we want to see if the key +`2` has a value associated with it. If it doesn't, we want to insert the value +"world". In both cases, we want to return the resulting value that now goes +with `2`. With the entry API, it looks like this: ```rust use std::collections::HashMap; @@ -111,9 +167,60 @@ let mut map = HashMap::new(); map.insert(1, "hello"); -let e = map.entry(2).or_insert("world"); +map.entry(2).or_insert("world"); +map.entry(1).or_insert("Hi There"); + +println!("{:?}", map); ``` -The `or_insert` method on entry does exactly this: returns the value, and if -not, inserts its argument and returns that. This is much cleaner than writing -the logic yourself, and in addition, plays more nicely with the borrow checker. +The `or_insert` method on `Entry` does exactly this: returns the value for the +`Entry`'s key if it exists, and if not, inserts its argument as the new value +for the `Entry`'s key and returns that. This is much cleaner than writing the +logic yourself, 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 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 +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 +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`. + +```rust +use std::collections::HashMap; + +let text = "hello world wonderful world"; + +let mut map = HashMap::new(); + +for word in text.split_whitespace() { + let count = map.entry(word).or_insert(0); + *count += 1; +} + +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` +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 +borrowing rules. + +## Hashing Function + +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 +your code and find that the default hash function is too slow for your +purposes, you can switch to another function by specifying a different +*hasher*. A hasher is an object that implements the `BuildHasher` trait. We'll +be talking about traits and how to implement them in Chapter XX. From 9ba5bb36901fdd2b3851d871bc18360e1bc7484e Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 19 Sep 2016 11:09:06 -0400 Subject: [PATCH 18/34] Make the filename and header more consistent --- src/SUMMARY.md | 2 +- src/{ch08-03-hash-map.md => ch08-03-hashmaps.md} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename src/{ch08-03-hash-map.md => ch08-03-hashmaps.md} (100%) diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 7aff0fa83..120199263 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -34,7 +34,7 @@ - [Essential Collections](ch08-00-essential-collections.md) - [Vectors](ch08-01-vectors.md) - [Strings](ch08-02-strings.md) - - [`HashMap`](ch08-03-hash-map.md) + - [HashMaps](ch08-03-hashmaps.md) - [Error Handling]() diff --git a/src/ch08-03-hash-map.md b/src/ch08-03-hashmaps.md similarity index 100% rename from src/ch08-03-hash-map.md rename to src/ch08-03-hashmaps.md From 00e5b22d9e21c32803be1c924bffd1bf2b9ba33f Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 19 Sep 2016 12:44:32 -0400 Subject: [PATCH 19/34] Remove irrelevant space special casing I think this confuses more than helps. --- src/ch08-02-strings.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/ch08-02-strings.md b/src/ch08-02-strings.md index 8bbe480de..d6dedccd0 100644 --- a/src/ch08-02-strings.md +++ b/src/ch08-02-strings.md @@ -252,31 +252,31 @@ expect: `&"hello"[0]` would then return `104`, not `h`. This leads to another point about UTF-8: there are really three relevant ways to look at strings, from Rust's perspective: bytes, scalar values, and grapheme -clusters. If we look at the string "नमस्ते ", it is ultimately stored as a `Vec` +clusters. If we look at the string "नमस्ते", it is ultimately stored as a `Vec` of `u8` values that looks like this: ```text -[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135, 32] +[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135] ``` -That's 19 bytes. But if we look at them as Unicode scalar values, which are +That's 18 bytes. But if we look at them as Unicode scalar values, which are what Rust's `char` type is, those bytes look like this: ```text -['न', 'म', 'स', '्', 'त', 'े', ' '] +['न', 'म', 'स', '्', 'त', 'े'] ``` -There are seven `char` values here, and the last one isn't even visible! -Finally, if we look at them as grapheme clusters, which is the closest thing -to what humans would call 'letters', we'd get this: +There are six `char` values here. Finally, if we look at them as grapheme +clusters, which is the closest thing to what humans would call 'letters', we'd +get this: ```text -["न", "म", "स्", "ते", " "] +["न", "म", "स्", "ते"] ``` -Five elements, and there's still that empty character on the end. It turns out -that even within 'grapheme cluster', there are multiple ways of grouping -things. Have we convinced you strings are actually really complicated yet? +Four elements! It turns out that even within 'grapheme cluster', there are +multiple ways of grouping things. Have we convinced you strings are actually +really complicated yet? All of these problems mean that Rust does not implement `[]` for `String`, so we cannot directly do this. From ccd4dcf1788134587992b95a8bce9dc935e18baa Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 19 Sep 2016 22:37:06 -0400 Subject: [PATCH 20/34] More edits and some TODOs for strings --- src/ch08-02-strings.md | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/ch08-02-strings.md b/src/ch08-02-strings.md index d6dedccd0..ddeb866d7 100644 --- a/src/ch08-02-strings.md +++ b/src/ch08-02-strings.md @@ -250,6 +250,8 @@ should `answer` be `208`? `208` is not a valid character on its own, though. Plus, for latin letters, this would not return the answer most people would expect: `&"hello"[0]` would then return `104`, not `h`. +### Bytes, and Scalar Values, and Grapheme Clusters! Oh my! + This leads to another point about UTF-8: there are really three relevant ways to look at strings, from Rust's perspective: bytes, scalar values, and grapheme clusters. If we look at the string "नमस्ते", it is ultimately stored as a `Vec` @@ -281,10 +283,11 @@ really complicated yet? All of these problems mean that Rust does not implement `[]` for `String`, so we cannot directly do this. -However. +## Slicing Strings -Sometimes, indexing the bytes of a string is useful. So while you can't use `[]` -with a single number, you _can_ use `[]` with a range: +However, indexing the bytes of a string is very useful. While you can't use +`[]` with a single number, you _can_ use `[]` with a range to create a string +slice from particular bytes: ```rust let hello = "Здравствуйте"; @@ -294,8 +297,19 @@ let s = &hello[0..4]; Here, `s` will be a `&str` that contains the first four bytes of the string. Earlier, we mentioned that each of these characters was two bytes, so that means -that `s` will be 'Зд'. +that `s` will be "Зд". What would happen if we did `&hello[0..1]`? We said each of these characters -required two bytes. The answer: it will panic, in the same way that accessing -an invalid index in a vector does. +required two bytes. The answer: it will panic at runtime, in the same way that +accessing an invalid index in a vector does: + +```bash +thread 'main' panicked at 'index 0 and/or 1 in `Здравствуйте` do not lie on +character boundary', ../src/libcore/str/mod.rs:1694 +``` + +## Methods for Iterating Over Strings + +TODO: Add examples of using `bytes`, `chars`, since those are recommended? + +TODO: summary that ties this to the next chapter From be6a7d55a6b5402a07ef65ba5f4e6afe3a4a09f3 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 12:53:42 -0400 Subject: [PATCH 21/34] Add a chapter summary --- src/ch08-03-hashmaps.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/ch08-03-hashmaps.md b/src/ch08-03-hashmaps.md index 78aaad3f7..966e42599 100644 --- a/src/ch08-03-hashmaps.md +++ b/src/ch08-03-hashmaps.md @@ -224,3 +224,28 @@ your code and find that the default hash function is too slow for your purposes, you can switch to another function by specifying a different *hasher*. A hasher is an object that implements the `BuildHasher` trait. We'll be talking about traits and how to implement them in Chapter XX. + +## Summary + +Vectors, Strings, and HashMaps 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), + 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 + 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 + 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 + alphabetically. + +The standard library API documentation describes methods these types have that +will be helpful for these exercises! + +We're getting into more complex programs where operations can fail, which means +it's a perfect time to go over error handling next! From 50acc06a9b19f718c5769e105aab781b957f8642 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 14:05:44 -0400 Subject: [PATCH 22/34] Round off Strings section - I think I finally get why there's no indexing but there is slicing - Show what you're actually supposed to do with chars and bytes - Summarize and transition --- src/ch08-02-strings.md | 71 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 62 insertions(+), 9 deletions(-) diff --git a/src/ch08-02-strings.md b/src/ch08-02-strings.md index ddeb866d7..35f7999ea 100644 --- a/src/ch08-02-strings.md +++ b/src/ch08-02-strings.md @@ -250,7 +250,7 @@ should `answer` be `208`? `208` is not a valid character on its own, though. Plus, for latin letters, this would not return the answer most people would expect: `&"hello"[0]` would then return `104`, not `h`. -### Bytes, and Scalar Values, and Grapheme Clusters! Oh my! +### Bytes and Scalar Values and Grapheme Clusters! Oh my! This leads to another point about UTF-8: there are really three relevant ways to look at strings, from Rust's perspective: bytes, scalar values, and grapheme @@ -280,14 +280,20 @@ Four elements! It turns out that even within 'grapheme cluster', there are multiple ways of grouping things. Have we convinced you strings are actually really complicated yet? +Another reason that indexing into a `String` to get a character is not available +is that indexing operations are expected to always be fast. This isn't possible +with a `String`, since Rust would have to walk through the contents from the +beginning to the index to determine how many valid characters there were, no +matter how we define "character". + All of these problems mean that Rust does not implement `[]` for `String`, so we cannot directly do this. ## Slicing Strings -However, indexing the bytes of a string is very useful. While you can't use -`[]` with a single number, you _can_ use `[]` with a range to create a string -slice from particular bytes: +However, indexing the bytes of a string is very useful, and is not expected to +be fast. While you can't use `[]` with a single number, you _can_ use `[]` with +a range to create a string slice from particular bytes: ```rust let hello = "Здравствуйте"; @@ -299,9 +305,8 @@ Here, `s` will be a `&str` that contains the first four bytes of the string. Earlier, we mentioned that each of these characters was two bytes, so that means that `s` will be "Зд". -What would happen if we did `&hello[0..1]`? We said each of these characters -required two bytes. The answer: it will panic at runtime, in the same way that -accessing an invalid index in a vector does: +What would happen if we did `&hello[0..1]`? The answer: it will panic at +runtime, in the same way that accessing an invalid index in a vector does: ```bash thread 'main' panicked at 'index 0 and/or 1 in `Здравствуйте` do not lie on @@ -310,6 +315,54 @@ character boundary', ../src/libcore/str/mod.rs:1694 ## Methods for Iterating Over Strings -TODO: Add examples of using `bytes`, `chars`, since those are recommended? +If we do need to perform operations on individual characters, the best way to do that is using the `chars` method. Calling `chars` on "नमस्ते" gives us the six Rust `char` values: -TODO: summary that ties this to the next chapter +```rust +for c in "नमस्ते".chars() { + println!("{}", c); +} +``` + +This code will print: + +```bash +न +म +स +् +त +े +``` + +The `bytes` method returns each raw byte, which might be appropriate for your +domain, but remember that valid UTF-8 characters may be made up of more than +one byte: + +```rust +for b in "नमस्ते".bytes() { + println!("{}", b); +} +``` + +This code will print the 18 bytes that make up this `String`, starting with: + +```bash +224 +164 +168 +224 +// ... etc +``` + +There are crates available to get grapheme clusters from `String`s. + +To summarize, strings are complicated. Different programming languages make +different choices about how to present this complexity to the programmer. Rust +has chosen to attempt to make correct handling of `String` data be the default +for all Rust programs, which does mean programmers have to put more thought +into handling UTF-8 data upfront. This tradeoff exposes us to more of the +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! From dcccf74b80a148115f6506da45475a6162da8821 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 14:08:25 -0400 Subject: [PATCH 23/34] Bump in headings a level --- src/ch08-01-vectors.md | 10 +++++----- src/ch08-02-strings.md | 26 ++++++++++++++------------ src/ch08-03-hashmaps.md | 16 ++++++++-------- 3 files changed, 27 insertions(+), 25 deletions(-) diff --git a/src/ch08-01-vectors.md b/src/ch08-01-vectors.md index 5e15885f9..1e511c1a7 100644 --- a/src/ch08-01-vectors.md +++ b/src/ch08-01-vectors.md @@ -1,10 +1,10 @@ -# Vectors +## Vectors The first type we'll look at is `Vec`, also known as a *vector*. Vectors allow you to store more than one value in a single data structure that puts all the values next to each other in memory. -## Creating a New Vector +### Creating a New Vector To create a new vector, you can call the `new` function: @@ -24,7 +24,7 @@ That said, in real code, you very rarely need to do this type annotation since Rust can infer the type of value we want to store once we insert values. Let's look at how to modify a vector next. -## Updating a Vector +### Updating a Vector To put elements in the vector, we can use the `push` method: @@ -50,7 +50,7 @@ let v = vec![5, 6, 7, 8]; This macro does a similar thing to our previous example, but it's much more convenient. -## Dropping a Vector Drops its Elements +### Dropping a Vector Drops its Elements Like any other `struct`, a vector will be freed when it goes out of scope: @@ -68,7 +68,7 @@ integers are going to be cleaned up as well. This may seem like a straightforward point, but can get a little more complicated once we start to introduce references to the elements of the vector. Let's tackle that next! -## Reading Elements of Vectors +### Reading Elements of Vectors Now that we know how creating and destroying vectors works, knowing how to read their contents is a good next step. There are two ways to reference a value diff --git a/src/ch08-02-strings.md b/src/ch08-02-strings.md index 35f7999ea..e09396c97 100644 --- a/src/ch08-02-strings.md +++ b/src/ch08-02-strings.md @@ -1,9 +1,9 @@ -# Strings +## Strings We've already talked about strings a bunch in Chapter 4, but let's take a more in-depth look at them now. -## Many Kinds of Strings +### Many Kinds of Strings Strings are a common place for new Rustaceans to get stuck. This is due to a combination of three things: Rust's propensity for making sure to expose @@ -33,7 +33,7 @@ represented in memory in a different way, for example. We won't be talking about these other string types in this chapter; see their API documentation for more about how to use them and when each is appropriate. -## Creating a New String +### Creating a New String Let's look at how to do the same operations on `String` as we did with `Vec`, starting with creating one. Similarly, `String` has `new`: @@ -85,11 +85,11 @@ let hello = "Здравствуйте"; let hello = "Hola"; ``` -## Updating a String +### Updating a String A `String` can be changed and can grow in size, just like a `Vec` can. -### Push +#### Push You can grow a `String` by using the `push_str` method to append another string: @@ -119,7 +119,7 @@ s.clear(); Now `s` will be the empty string, "". -### Concatenation +#### Concatenation Often, you'll want to combine two strings together. One way is to use the `+` operator: @@ -187,7 +187,7 @@ same way as `println!`, but instead of printing the output to the screen, it returns a `String` with the contents. This version is much easier to read than all of the `+`s. -## Indexing into Strings +### Indexing into Strings In many other languages, accessing individual characters in a string by referencing the characters by index is a valid and common operation. In Rust, @@ -214,7 +214,7 @@ The error and the note tell the story: Rust strings don't support indexing. So the follow-up question is, why not? In order to answer that, we have to talk a bit about how Rust stores strings in memory. -### Internal Representation +#### Internal Representation A `String` is a wrapper over a `Vec`. Let's take a look at some of our properly-encoded UTF-8 example strings from before. First, this one: @@ -250,7 +250,7 @@ should `answer` be `208`? `208` is not a valid character on its own, though. Plus, for latin letters, this would not return the answer most people would expect: `&"hello"[0]` would then return `104`, not `h`. -### Bytes and Scalar Values and Grapheme Clusters! Oh my! +#### Bytes and Scalar Values and Grapheme Clusters! Oh my! This leads to another point about UTF-8: there are really three relevant ways to look at strings, from Rust's perspective: bytes, scalar values, and grapheme @@ -289,7 +289,7 @@ matter how we define "character". All of these problems mean that Rust does not implement `[]` for `String`, so we cannot directly do this. -## Slicing Strings +### Slicing Strings However, indexing the bytes of a string is very useful, and is not expected to be fast. While you can't use `[]` with a single number, you _can_ use `[]` with @@ -313,9 +313,11 @@ thread 'main' panicked at 'index 0 and/or 1 in `Здравствуйте` do not character boundary', ../src/libcore/str/mod.rs:1694 ``` -## Methods for Iterating Over Strings +### Methods for Iterating Over Strings -If we do need to perform operations on individual characters, the best way to do that is using the `chars` method. Calling `chars` on "नमस्ते" gives us the six Rust `char` values: +If we do need to perform operations on individual characters, the best way to +do that is using the `chars` method. Calling `chars` on "नमस्ते" gives us the six +Rust `char` values: ```rust for c in "नमस्ते".chars() { diff --git a/src/ch08-03-hashmaps.md b/src/ch08-03-hashmaps.md index 966e42599..138a36c45 100644 --- a/src/ch08-03-hashmaps.md +++ b/src/ch08-03-hashmaps.md @@ -1,4 +1,4 @@ -# HashMaps +## HashMaps The last of our essential collections is the *HashMap*. A `HashMap` stores a mapping of keys of type `K` to values of type `V`. It does this via a @@ -11,7 +11,7 @@ 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, check the standard library documentation for more information. -## Creating a HashMap +### Creating a HashMap We can create an empty HashMap with `new`, and add elements with `insert`: @@ -76,7 +76,7 @@ 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 in the Lifetimes section of Chapter XX. -## Accessing Values in a HashMap +### Accessing Values in a HashMap We can get a value out of the HashMap by providing its key to the `get` method: @@ -119,9 +119,9 @@ This will print: 2: world ``` -## Updating a HashMap +### Updating a HashMap -### Overwriting a Value +#### Overwriting a Value If you 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: @@ -138,7 +138,7 @@ println!("{:?}", map); This will print `{1: "Hi There"}`. -### Only Insert If the Key Has No Value +#### 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 @@ -183,7 +183,7 @@ 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 has the value "hello". -### Update a Value Based on the Old Value +#### Update a Value Based on the Old Value Another common use case for HashMaps 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 @@ -214,7 +214,7 @@ variable binding, so in order to assign to that value we must first dereference the end of the `for` loop, so all of these changes are safe and allowed by the borrowing rules. -## Hashing Function +### Hashing Function By default, HashMap uses a cryptographically secure hashing function that can provide resistance to Denial of Service (DoS) attacks. This is not the fastest From b168c614a210fe2516d152991a6a99efc0529a57 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 14:19:48 -0400 Subject: [PATCH 24/34] Talk about how dropping of a Vec affects references into the vec More explicitly than the adding-while-reading example. --- src/ch08-01-vectors.md | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/src/ch08-01-vectors.md b/src/ch08-01-vectors.md index 1e511c1a7..3e25523a0 100644 --- a/src/ch08-01-vectors.md +++ b/src/ch08-01-vectors.md @@ -107,9 +107,31 @@ and your code will have logic to handle getting `Some(&element)` or `None`. Once we have a valid reference, the borrow checker will enforce the ownership and borrowing rules we covered in Chapter 4 in order to ensure this and other -references to the contents of the vector stay valid. For example, here's code -that looks like it should be allowed, but it won't compile because the -references actually aren't valid anymore: +references to the contents of the vector stay valid. This means in a function +that owns a `Vec`, we can't return a reference to an element since the `Vec` +will be cleaned up at the end of the function: + +```rust,ignore +fn element() -> String { + let list = vec![String::from("hi"), String::from("bye")]; + list[1] +} +``` + +Trying to compile this will result in the following error: + +```bash +error: cannot move out of indexed content [--explain E0507] + |> +4 |> list[1] + |> ^^^^^^^ cannot move out of indexed content +``` + +Since `list` goes out of scope and gets cleaned up at the end of the function, +the reference `list[1]` cannot be returned because it would outlive `list`. + +Here's another example of code that looks like it should be allowed, but it +won't compile because the references actually aren't valid anymore: ```rust,ignore let mut v = vec![1, 2, 3, 4, 5]; From 6bef3b89cf240dc5506f57da8802c1ea55031e77 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 15:17:25 -0400 Subject: [PATCH 25/34] Small wording tweaks, mostly removing 'you' --- src/ch08-00-essential-collections.md | 4 +- src/ch08-01-vectors.md | 16 +++---- src/ch08-02-strings.md | 66 ++++++++++++++-------------- src/ch08-03-hashmaps.md | 6 +-- 4 files changed, 46 insertions(+), 46 deletions(-) diff --git a/src/ch08-00-essential-collections.md b/src/ch08-00-essential-collections.md index 7eea35bd3..7d3a89475 100644 --- a/src/ch08-00-essential-collections.md +++ b/src/ch08-00-essential-collections.md @@ -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 you to store a variable number of values next to each other. +* 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 you to associate a value with a particular key. +* A *HashMap* 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 diff --git a/src/ch08-01-vectors.md b/src/ch08-01-vectors.md index 3e25523a0..af2a463a7 100644 --- a/src/ch08-01-vectors.md +++ b/src/ch08-01-vectors.md @@ -1,26 +1,26 @@ ## Vectors The first type we'll look at is `Vec`, also known as a *vector*. Vectors -allow you to store more than one value in a single data structure that puts all +allow us to store more than one value in a single data structure that puts all the values next to each other in memory. ### Creating a New Vector -To create a new vector, you can call the `new` function: +To create a new vector, we can call the `new` function: ```rust let v: Vec = Vec::new(); ``` -You'll note that we added a type annotation here. Because we don't actually do +Note that we added a type annotation here. Since we don't actually do anything with the vector, Rust doesn't know what kind of elements we intend to store. This is an important point. Vectors are homogenous: they may store many values, but those values must all be the same type. Vectors are generic over -the type you store inside them (we'll talk about Generics more throroughly in +the type stored inside them (we'll talk about Generics more throroughly in Chapter XX), and the angle brackets here tell Rust that this vector will hold elements of the `i32` type. -That said, in real code, you very rarely need to do this type annotation since +That said, in real code, we very rarely need to do this type annotation since Rust can infer the type of value we want to store once we insert values. Let's look at how to modify a vector next. @@ -100,10 +100,10 @@ let does_not_exist = v.get(100); With the `[]`s, Rust will cause a `panic!`. With the `get` method, it will instead return `None` without `panic!`ing. Deciding which way to access -elements in a vector depends on whether you consider an attempted access past -the end of the vector to be an error, in which case you would want the `panic!` +elements in a vector depends on whether we consider an attempted access past +the end of the vector to be an error, in which case we'd want the `panic!` behavior, or whether this will happen occasionally under normal circumstances -and your code will have logic to handle getting `Some(&element)` or `None`. +and our code will have logic to handle getting `Some(&element)` or `None`. Once we have a valid reference, the borrow checker will enforce the ownership and borrowing rules we covered in Chapter 4 in order to ensure this and other diff --git a/src/ch08-02-strings.md b/src/ch08-02-strings.md index e09396c97..c5f351d4c 100644 --- a/src/ch08-02-strings.md +++ b/src/ch08-02-strings.md @@ -9,16 +9,16 @@ Strings are a common place for new Rustaceans to get stuck. This is due to a combination of three things: Rust's propensity for making sure to expose possible errors, strings being a more complicated data structure than many programmers give them credit for, and UTF-8. These things combine in a way that -can seem difficult when you're used to other languages. +can seem difficult coming from other languages. -Before we can dig into those things, we need to talk about what exactly we even -mean by the word 'string'. Rust-the-language has only one string type: `&str`. -We talked about these string slices in Chapter 4: they're a reference to some -UTF-8 encoded string data stored somewhere else. String literals, for example, -are stored in the binary output of your program, and are therefore string -slices. +Before we can dig into those aspects, we need to talk about what exactly we +even mean by the word 'string'. Rust actually only has one string type in the +core language itself: `&str`. We talked about these string slices in Chapter 4: +they're a reference to some UTF-8 encoded string data stored somewhere else. +String literals, for example, are stored in the binary output of the program, +and are therefore string slices. -Rust's standard library also provides a type called `String`. This is a +Rust's standard library is what provides the type called `String`. This is a growable, mutable, owned, UTF-8 encoded string type. When Rustaceans talk about 'strings' in Rust, they usually mean "`String` and `&str`". This chapter is largely about `String`, and these two types are used heavily in Rust's standard @@ -26,12 +26,12 @@ library. Both `String` and string slices are UTF-8 encoded. Rust's standard library also includes a number of other string types, such as `OsString`, `OsStr`, `CString`, and `CStr`. Library crates may provide even -more options for storing string data. As you can see from the `*String`/`*Str` -naming, they often provide an owned and borrowed variant, just like -`String`/`&str`. These string types may store different encodings or be -represented in memory in a different way, for example. We won't be talking -about these other string types in this chapter; see their API documentation for -more about how to use them and when each is appropriate. +more options for storing string data. Similarly to the `*String`/`*Str` naming, +they often provide an owned and borrowed variant, just like `String`/`&str`. +These string types may store different encodings or be represented in memory in +a different way, for example. We won't be talking about these other string +types in this chapter; see their API documentation for more about how to use +them and when each is appropriate. ### Creating a New String @@ -42,8 +42,8 @@ starting with creating one. Similarly, `String` has `new`: let s = String::new(); ``` -Often, you have some initial data that you'd like to start the string off with. -For that, there's the `.to_string()` method: +Often, we'll have some initial data that we'd like to start the string off with. +For that, there's the `to_string` method: ```rust let data = "initial contents"; @@ -54,13 +54,13 @@ let s = data.to_string(); let s = "initial contents".to_string(); ``` -You'll also see this form sometimes: +This form is equivalent to using `to_string`: ```rust let s = String::from("Initial contents"); ``` -Because strings are used for so many things, there are many different generic +Since strings are used for so many things, there are many different generic APIs that make sense for strings. There are a lot of options, and some of them can feel redundant because of this, but they all have their place! In this case, `String::from` and `.to_string` end up doing the exact same thing, so @@ -68,8 +68,8 @@ which you choose is a matter of style. Some people use `String::from` for literals, and `.to_string` for variable bindings. Most Rust style is pretty uniform, but this specific question is one of the most debated. -Don't forget that strings are UTF-8 encoded, so you can include any -properly encoded data in them: +Remember that strings are UTF-8 encoded, so we can include any properly encoded +data in them: ```rust let hello = "السلام عليكم"; @@ -91,7 +91,7 @@ A `String` can be changed and can grow in size, just like a `Vec` can. #### Push -You can grow a `String` by using the `push_str` method to append another +We can grow a `String` by using the `push_str` method to append another string: ```rust @@ -110,7 +110,7 @@ s.push('l'); `s` will contain "lol" after this point. -You can make any `String` contain the empty string with the `clear` method: +We can make any `String` contain the empty string with the `clear` method: ```rust let mut s = String::from("Noooooooooooooooooooooo!"); @@ -121,7 +121,7 @@ Now `s` will be the empty string, "". #### Concatenation -Often, you'll want to combine two strings together. One way is to use the `+` +Often, we'll want to combine two strings together. One way is to use the `+` operator: ```rust @@ -144,11 +144,11 @@ signature of the method would be if `add` was defined specifically for `String`. This signature gives us the clues we need in order to understand the tricky bits of `+`. -First of all, you'll notice that `s2` has an `&`. This is because of the `s` -argument in the `add` function: you can only add a `&str` to a `String`, you -can't add two `String`s together. Remember back in Chapter 4 when we talked -about how `&String` will coerce to `&str`: we write `&s2` so that the `String` -will coerce to the proper type, `&str`. +First of all, `s2` has an `&`. This is because of the `s` argument in the `add` +function: we can only add a `&str` to a `String`, we can't add two `String`s +together. Remember back in Chapter 4 when we talked about how `&String` will +coerce to `&str`: we write `&s2` so that the `String` will coerce to the proper +type, `&str`. Secondly, `add` takes ownership of `self`, which we can tell because `self` does *not* have an `&` in the signature. This means `s1` in the above example @@ -159,7 +159,7 @@ new one, this statement actually takes ownership of `s1`, appends a copy of like it's making a lot of copies, but isn't: the implementation is more efficient than copying. -If you need to concatenate multiple strings, this behavior of `+` gets +If we need to concatenate multiple strings, this behavior of `+` gets unwieldy: ```rust @@ -245,7 +245,7 @@ let answer = &h[0]; ``` What should the value of `answer` be? Should it be `З`, the first letter? When -you encode `З` in UTF-8, the first byte is `208`, and the second is `151`. So +encoded in UTF-8, the first byte of `З` is `208`, and the second is `151`. So should `answer` be `208`? `208` is not a valid character on its own, though. Plus, for latin letters, this would not return the answer most people would expect: `&"hello"[0]` would then return `104`, not `h`. @@ -277,8 +277,8 @@ get this: ``` Four elements! It turns out that even within 'grapheme cluster', there are -multiple ways of grouping things. Have we convinced you strings are actually -really complicated yet? +multiple ways of grouping things. Convinced that strings are actually really +complicated yet? Another reason that indexing into a `String` to get a character is not available is that indexing operations are expected to always be fast. This isn't possible @@ -292,7 +292,7 @@ we cannot directly do this. ### Slicing Strings However, indexing the bytes of a string is very useful, and is not expected to -be fast. While you can't use `[]` with a single number, you _can_ use `[]` with +be fast. While we can't use `[]` with a single number, we _can_ use `[]` with a range to create a string slice from particular bytes: ```rust diff --git a/src/ch08-03-hashmaps.md b/src/ch08-03-hashmaps.md index 138a36c45..74d798740 100644 --- a/src/ch08-03-hashmaps.md +++ b/src/ch08-03-hashmaps.md @@ -35,7 +35,7 @@ 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. -If you have a vector of tuples, you can convert it into a HashMap with the +If we have a vector of tuples, we can convert it into a HashMap with the `collect` method. The first element in each tuple will be the key, and the second element will be the value: @@ -123,7 +123,7 @@ This will print: #### Overwriting a Value -If you 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 HashMap will only contain one key/value pair, since we're inserting with the key `1` both times: ```rust use std::collections::HashMap; @@ -176,7 +176,7 @@ println!("{:?}", map); The `or_insert` method on `Entry` does exactly this: returns the value for the `Entry`'s key if it exists, and if not, inserts its argument as the new value for the `Entry`'s key and returns that. This is much cleaner than writing the -logic yourself, and in addition, plays more nicely with the borrow checker. +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 From 0812f3a0e26955cade88f287ede3e62fa5a68b37 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 15:26:35 -0400 Subject: [PATCH 26/34] Fill in some chapter numbers we know now --- src/ch08-01-vectors.md | 2 +- src/ch08-03-hashmaps.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ch08-01-vectors.md b/src/ch08-01-vectors.md index af2a463a7..be033291f 100644 --- a/src/ch08-01-vectors.md +++ b/src/ch08-01-vectors.md @@ -17,7 +17,7 @@ anything with the vector, Rust doesn't know what kind of elements we intend to store. This is an important point. Vectors are homogenous: they may store many values, but those values must all be the same type. Vectors are generic over the type stored inside them (we'll talk about Generics more throroughly in -Chapter XX), and the angle brackets here tell Rust that this vector will hold +Chapter 10), and the angle brackets here tell Rust that this vector will hold elements of the `i32` type. That said, in real code, we very rarely need to do this type annotation since diff --git a/src/ch08-03-hashmaps.md b/src/ch08-03-hashmaps.md index 74d798740..867d2caf1 100644 --- a/src/ch08-03-hashmaps.md +++ b/src/ch08-03-hashmaps.md @@ -74,7 +74,7 @@ they have been moved into the HashMap 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 -in the Lifetimes section of Chapter XX. +in the Lifetimes section of Chapter 10. ### Accessing Values in a HashMap @@ -223,7 +223,7 @@ with the drop in performance is a good default tradeoff to make. If you profile your code and find that the default hash function is too slow for your purposes, you can switch to another function by specifying a different *hasher*. A hasher is an object that implements the `BuildHasher` trait. We'll -be talking about traits and how to implement them in Chapter XX. +be talking about traits and how to implement them in Chapter 10. ## Summary From c3ddfa5c44381376ec86388e159f22d4c8f8cf26 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 22:22:09 -0400 Subject: [PATCH 27/34] No more essence. anywhere. There is no essence. --- src/SUMMARY.md | 2 +- ...tial-collections.md => ch08-00-fundamental-collections.md} | 2 +- src/ch08-03-hashmaps.md | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) rename src/{ch08-00-essential-collections.md => ch08-00-fundamental-collections.md} (97%) diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 120199263..e90af8963 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -31,7 +31,7 @@ - [Controlling visibility with `pub`](ch07-02-controlling-visibility-with-pub.md) - [Importing names with `use`](ch07-03-importing-names-with-use.md) -- [Essential Collections](ch08-00-essential-collections.md) +- [Fundamental Collections](ch08-00-fundamental-collections.md) - [Vectors](ch08-01-vectors.md) - [Strings](ch08-02-strings.md) - [HashMaps](ch08-03-hashmaps.md) diff --git a/src/ch08-00-essential-collections.md b/src/ch08-00-fundamental-collections.md similarity index 97% rename from src/ch08-00-essential-collections.md rename to src/ch08-00-fundamental-collections.md index 7d3a89475..29044dd42 100644 --- a/src/ch08-00-essential-collections.md +++ b/src/ch08-00-fundamental-collections.md @@ -1,4 +1,4 @@ -# Essential Collections +# Fundamental Collections Rust's standard library includes a number of really useful data structures called *collections*. Most other types represent one specific value, but diff --git a/src/ch08-03-hashmaps.md b/src/ch08-03-hashmaps.md index 867d2caf1..fd8a92b0b 100644 --- a/src/ch08-03-hashmaps.md +++ b/src/ch08-03-hashmaps.md @@ -1,6 +1,6 @@ ## HashMaps -The last of our essential collections is the *HashMap*. A `HashMap` +The last of our fundamental collections is the *HashMap*. A `HashMap` 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 @@ -25,7 +25,7 @@ map.insert(2, "world"); ``` Note that we need to `use` the `HashMap` from the collections portion of the -standard library. Of our three essential collections, this one is the least +standard library. Of our three fundamental collections, this one is the least 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. From d56e5367cb07c91ef66f8f3304f8fb2ce23bb3bc Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 22:31:27 -0400 Subject: [PATCH 28/34] You've got your big G's, I've got my hash map --- src/SUMMARY.md | 2 +- src/ch08-00-fundamental-collections.md | 8 +-- src/ch08-02-strings.md | 2 +- ...08-03-hashmaps.md => ch08-03-hash-maps.md} | 72 +++++++++---------- 4 files changed, 42 insertions(+), 42 deletions(-) rename src/{ch08-03-hashmaps.md => ch08-03-hash-maps.md} (71%) diff --git a/src/SUMMARY.md b/src/SUMMARY.md index e90af8963..a77b9d6df 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -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]() diff --git a/src/ch08-00-fundamental-collections.md b/src/ch08-00-fundamental-collections.md index 29044dd42..3ab024a21 100644 --- a/src/ch08-00-fundamental-collections.md +++ b/src/ch08-00-fundamental-collections.md @@ -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 diff --git a/src/ch08-02-strings.md b/src/ch08-02-strings.md index c5f351d4c..19016e68d 100644 --- a/src/ch08-02-strings.md +++ b/src/ch08-02-strings.md @@ -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! diff --git a/src/ch08-03-hashmaps.md b/src/ch08-03-hash-maps.md similarity index 71% rename from src/ch08-03-hashmaps.md rename to src/ch08-03-hash-maps.md index fd8a92b0b..f471dbe3f 100644 --- a/src/ch08-03-hashmaps.md +++ b/src/ch08-03-hash-maps.md @@ -1,19 +1,19 @@ -## HashMaps +## Hash Maps -The last of our fundamental collections is the *HashMap*. A `HashMap` -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` 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`. If there's no value for that key in the HashMap, `get` will +an `Option`. 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 From 021998f19378138ec9e5cc8826d69c5303a82961 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 22:37:12 -0400 Subject: [PATCH 29/34] The word of the day is *string slice* --- src/ch08-02-strings.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ch08-02-strings.md b/src/ch08-02-strings.md index 19016e68d..298009e14 100644 --- a/src/ch08-02-strings.md +++ b/src/ch08-02-strings.md @@ -13,7 +13,7 @@ can seem difficult coming from other languages. Before we can dig into those aspects, we need to talk about what exactly we even mean by the word 'string'. Rust actually only has one string type in the -core language itself: `&str`. We talked about these string slices in Chapter 4: +core language itself: `&str`. We talked about *string slices* in Chapter 4: they're a reference to some UTF-8 encoded string data stored somewhere else. String literals, for example, are stored in the binary output of the program, and are therefore string slices. From 2d5ea64dd5e5a76394a500ed23552e1e5c502db4 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 22:37:23 -0400 Subject: [PATCH 30/34] Crates for the crates.io! --- src/ch08-02-strings.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ch08-02-strings.md b/src/ch08-02-strings.md index 298009e14..801cda8ec 100644 --- a/src/ch08-02-strings.md +++ b/src/ch08-02-strings.md @@ -356,7 +356,7 @@ This code will print the 18 bytes that make up this `String`, starting with: // ... etc ``` -There are crates available to get grapheme clusters from `String`s. +There are crates available on crates.io to get grapheme clusters from `String`s. To summarize, strings are complicated. Different programming languages make different choices about how to present this complexity to the programmer. Rust From 84b135da9f05c589c3087e3f8eef024e29715200 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 22:42:37 -0400 Subject: [PATCH 31/34] Add text between the headings --- src/ch08-03-hash-maps.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/ch08-03-hash-maps.md b/src/ch08-03-hash-maps.md index f471dbe3f..c53041b2f 100644 --- a/src/ch08-03-hash-maps.md +++ b/src/ch08-03-hash-maps.md @@ -121,6 +121,13 @@ This will print: ### Updating a Hash Map +Since each key can only have one value, when we want to change the data in a +hash map, we have to decide how to handle the case when a key already has a +value assigned. We could choose to replace the old value with the new value. We +could choose to keep the old value and ignore the new value, and only add the +new value if the key *doesn't* already have a value. Or we could change the +existing value. Let's look at how to do each of these! + #### 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 hash map will only contain one key/value pair, since we're inserting with the key `1` both times: From a7e3b2ae609c75dec7cb8692f90565590a4e692c Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 22:42:50 -0400 Subject: [PATCH 32/34] Wrap at 80 oops --- src/ch08-03-hash-maps.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/ch08-03-hash-maps.md b/src/ch08-03-hash-maps.md index c53041b2f..397b0f5b3 100644 --- a/src/ch08-03-hash-maps.md +++ b/src/ch08-03-hash-maps.md @@ -130,7 +130,10 @@ existing value. Let's look at how to do each of these! #### 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 hash map 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; From 7280821672d7ce45d8bd8a426850bf7240a96840 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 26 Sep 2016 23:16:40 -0400 Subject: [PATCH 33/34] Show how to store different types in an enum in a vec --- src/ch08-01-vectors.md | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/src/ch08-01-vectors.md b/src/ch08-01-vectors.md index be033291f..d926af211 100644 --- a/src/ch08-01-vectors.md +++ b/src/ch08-01-vectors.md @@ -167,7 +167,44 @@ put all the elements next to each other where the vector was. If this happened, our reference would be pointing to deallocated memory. For more on this, see [The Nomicon](https://doc.rust-lang.org/stable/nomicon/vec.html). -Be sure to take a look at the API documentation for all the methods defined on +### Using an Enum to Store Multiple Types + +Let's put vectors together with what we learned about enums in Chapter 6. At +the beginning of this section, we said that vectors will only store values that +are all the same type. This can be inconvenient; there are definitely use cases +for needing to store a list of things that might be different types. Luckily, +the variants of an enum are all the same type as each other, so when we're in +this scenario, we can define and use an enum! + +For example, let's say we're going to be getting values for a row in a +spreadsheet. Some of the columns contain integers, some floating point numbers, +and some strings. We can define an enum whose variants will hold the different +value types. All of the enum variants will then be the same type, that of the +enum. Then we can create a vector that, ultimately, holds different types: + +```rust +enum SpreadsheetCell { + Int(i32), + Float(f64), + Text(String), +} + +let row = vec![ + SpreadsheetCell::Int(3), + SpreadsheetCell::Text(String::from("blue")), + SpreadsheetCell::Float(10.12), +]; +``` + +This has the advantage of being explicit about what types are allowed in this +vector. If we allowed any type to be in a vector, there would be a chance that +the vector would hold a type that would cause errors with the operations we +performed on the vector. Using an enum plus a `match` where we access elements +in a vector like this means that Rust will ensure at compile time that we +always handle every possible case. + +Now that we've gone over some of the most common ways to use vectors, be sure +to take a look at the API documentation for other useful methods defined on `Vec` by the standard library. For example, in addition to `push` there's a `pop` method that will remove and return the last element. Let's move on to the next collection type: `String`! From d7a11ad3b63aa897c0a9fc0d10144a62a0cf7c24 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Tue, 27 Sep 2016 10:58:40 -0400 Subject: [PATCH 34/34] Paragraph foreshadowing trait objects --- src/ch08-01-vectors.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/ch08-01-vectors.md b/src/ch08-01-vectors.md index d926af211..6b5daac14 100644 --- a/src/ch08-01-vectors.md +++ b/src/ch08-01-vectors.md @@ -203,6 +203,11 @@ performed on the vector. Using an enum plus a `match` where we access elements in a vector like this means that Rust will ensure at compile time that we always handle every possible case. +Using an enum for storing different types in a vector does imply that we need +to know the set of types we'll want to store at compile time. If that's not the +case, instead of an enum, we can use a trait object. We'll learn about those in +Chapter XX. + Now that we've gone over some of the most common ways to use vectors, be sure to take a look at the API documentation for other useful methods defined on `Vec` by the standard library. For example, in addition to `push` there's a