mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 21:21:18 -06:00
Merge pull request #450 from rust-lang/ch8-tr
Ch8 edits after technical review
This commit is contained in:
+1
-2
@@ -100,9 +100,8 @@ growable
|
|||||||
hardcoded
|
hardcoded
|
||||||
hardcoding
|
hardcoding
|
||||||
hasher
|
hasher
|
||||||
hashmap
|
hashers
|
||||||
HashMap
|
HashMap
|
||||||
Hashmaps
|
|
||||||
Haskell
|
Haskell
|
||||||
hasn
|
hasn
|
||||||
helloworld
|
helloworld
|
||||||
|
|||||||
+188
-229
@@ -1,31 +1,33 @@
|
|||||||
|
|
||||||
[TOC]
|
[TOC]
|
||||||
|
|
||||||
# Fundamental Collections
|
# Common Collections
|
||||||
|
|
||||||
Rust's standard library includes a number of really useful data structures
|
Rust’s standard library includes a number of really useful data structures
|
||||||
called *collections*. Most other data types represent one specific value, but
|
called *collections*. Most other data types represent one specific value, but
|
||||||
collections can contain multiple values. Unlike the built-in array and tuple
|
collections can contain multiple values. Unlike the built-in array and tuple
|
||||||
types, the data these collections point to is stored on the heap, which means
|
types, the data these collections point to is stored on the heap, which means
|
||||||
the amount of data does not need to be known at compile time and can grow or
|
the amount of data does not need to be known at compile time and can grow or
|
||||||
shrink as the program runs. Each kind of collection has different capabilities
|
shrink as the program runs. Each kind of collection has different capabilities
|
||||||
and costs, and choosing an appropriate one for the situation you're in is a
|
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
|
skill you’ll develop over time. In this chapter, we’ll go over three
|
||||||
collections which are used very often in Rust programs:
|
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 *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
|
* A *string* is a collection of characters. We’ve seen the `String` type
|
||||||
before, but we'll talk about it in depth now.
|
before, but we’ll talk about it in depth now.
|
||||||
* A *hash map* allows us to associate a value with a particular key.
|
* A *hash map* allows us to associate a value with a particular key. It's a
|
||||||
|
particular implementation of the more general data structure called a *map*.
|
||||||
|
|
||||||
There are more specialized variants of each of these data structures for
|
To learn about the other kinds of collections provided by the standard library,
|
||||||
particular situations, but these are the most fundamental and common. We're
|
see the documentation at *https://doc.rust-lang.org/stable/std/collections*.
|
||||||
going to discuss how to create and update each of the collections, as well as
|
|
||||||
what makes each special.
|
We’re going to discuss how to create and update vectors, strings, and hash
|
||||||
|
maps, as well as what makes each special.
|
||||||
|
|
||||||
## Vectors
|
## Vectors
|
||||||
|
|
||||||
The first type we'll look at is `Vec<T>`, also known as a *vector*. Vectors
|
The first type we’ll look at is `Vec<T>`, also known as a *vector*. Vectors
|
||||||
allow us 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. Vectors can only store values of the
|
the values next to each other in memory. Vectors can only store values of the
|
||||||
same type. They are useful in situations where you have a list of items, such
|
same type. They are useful in situations where you have a list of items, such
|
||||||
@@ -39,18 +41,18 @@ To create a new, empty vector, we can call the `Vec::new` function:
|
|||||||
let v: Vec<i32> = Vec::new();
|
let v: Vec<i32> = Vec::new();
|
||||||
```
|
```
|
||||||
|
|
||||||
Note that we added a type annotation here. Since we aren't inserting any values
|
Note that we added a type annotation here. Since we aren’t inserting any values
|
||||||
into this vector, Rust doesn't know what kind of elements we intend to store.
|
into this 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,
|
This is an important point. Vectors are homogeneous: they may store many
|
||||||
but those values must all be the same type. Vectors are implemented using
|
values, but those values must all be the same type. Vectors are implemented
|
||||||
generics, which Chapter 10 will cover how to use in your own types. For now,
|
using generics, which Chapter 10 will cover how to use in your own types. For
|
||||||
all you need to know is that the `Vec` type provided by the standard library
|
now, all you need to know is that the `Vec` type provided by the standard
|
||||||
can hold any type, and when a specific `Vec` holds a specific type, the type
|
library can hold any type, and when a specific `Vec` holds a specific type, the
|
||||||
goes within angle brackets. We've told Rust that the `Vec` in `v` will hold
|
type goes within angle brackets. We’ve told Rust that the `Vec` in `v` will
|
||||||
elements of the `i32` type.
|
hold elements of the `i32` type.
|
||||||
|
|
||||||
In real code, Rust can infer the type of value we want to store once we insert
|
In real code, Rust can infer the type of value we want to store once we insert
|
||||||
values, so you rarely need to do this type annotation. It's more common to
|
values, so you rarely need to do this type annotation. It’s more common to
|
||||||
create a `Vec` that has initial values, and Rust provides the `vec!` macro for
|
create a `Vec` that has initial values, and Rust provides the `vec!` macro for
|
||||||
convenience. The macro will create a new `Vec` that holds the values we give
|
convenience. The macro will create a new `Vec` that holds the values we give
|
||||||
it. This will create a new `Vec<i32>` that holds the values `1`, `2`, and `3`:
|
it. This will create a new `Vec<i32>` that holds the values `1`, `2`, and `3`:
|
||||||
@@ -59,8 +61,8 @@ it. This will create a new `Vec<i32>` that holds the values `1`, `2`, and `3`:
|
|||||||
let v = vec![1, 2, 3];
|
let v = vec![1, 2, 3];
|
||||||
```
|
```
|
||||||
|
|
||||||
Because we've given initial `i32` values, Rust can infer that the type of `v`
|
Because we’ve given initial `i32` values, Rust can infer that the type of `v`
|
||||||
is `Vec<i32>`, and the type annotation isn't necessary. Let's look at how to
|
is `Vec<i32>`, and the type annotation isn’t necessary. Let’s look at how to
|
||||||
modify a vector next.
|
modify a vector next.
|
||||||
|
|
||||||
### Updating a Vector
|
### Updating a Vector
|
||||||
@@ -78,8 +80,8 @@ v.push(8);
|
|||||||
|
|
||||||
As with any variable as we discussed in Chapter 3, if we want to be able to
|
As with any variable as we discussed in Chapter 3, if we want to be able to
|
||||||
change its value, we need to make it mutable with the `mut` keyword. The
|
change its value, we need to make it mutable with the `mut` keyword. The
|
||||||
numbers we place inside are all `i32`s, and Rust infers this from the data, so
|
numbers we place inside are all of type `i32`, and Rust infers this from the
|
||||||
we don't need the `Vec<i32>` annotation.
|
data, so we don’t need the `Vec<i32>` annotation.
|
||||||
|
|
||||||
### Dropping a Vector Drops its Elements
|
### Dropping a Vector Drops its Elements
|
||||||
|
|
||||||
@@ -97,13 +99,13 @@ Like any other `struct`, a vector will be freed when it goes out of scope:
|
|||||||
When the vector gets dropped, all of its contents will also be dropped, meaning
|
When the vector gets dropped, all of its contents will also be dropped, meaning
|
||||||
those integers it holds will be cleaned up. This may seem like a
|
those integers it holds will be cleaned up. This may seem like a
|
||||||
straightforward point, but can get a little more complicated once we start to
|
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!
|
introduce references to the elements of the vector. Let’s tackle that next!
|
||||||
|
|
||||||
### Reading Elements of Vectors
|
### Reading Elements of Vectors
|
||||||
|
|
||||||
Now that you know how to create, update, and destroy vectors, knowing how to
|
Now that you know how to create, update, and destroy vectors, knowing how to
|
||||||
read their contents is a good next step. There are two ways to reference a
|
read their contents is a good next step. There are two ways to reference a
|
||||||
value stored in a vector. In the examples, we've annotated the types of the
|
value stored in a vector. In the examples, we’ve annotated the types of the
|
||||||
values that are returned from these functions for extra clarity.
|
values that are returned from these functions for extra clarity.
|
||||||
|
|
||||||
This example shows both methods of accessing a value in a vector either with
|
This example shows both methods of accessing a value in a vector either with
|
||||||
@@ -119,12 +121,12 @@ let third: Option<&i32> = v.get(2);
|
|||||||
There are a few things to note here. First, that we use the index value of `2`
|
There are a few things to note here. First, that we use the index value of `2`
|
||||||
to get the third element: vectors are indexed by number, starting at zero.
|
to get the third element: vectors are indexed by number, starting at zero.
|
||||||
Second, the two different ways to get the third element are: using `&` and
|
Second, the two different ways to get the third element are: using `&` and
|
||||||
`[]`s, which gives us a reference, or using the `get` method with the index
|
`[]`, which gives us a reference, or using the `get` method with the index
|
||||||
passed as an argument, which gives us an `Option<&T>`.
|
passed as an argument, which gives us an `Option<&T>`.
|
||||||
|
|
||||||
The reason Rust has two ways to reference an element is so that you can choose
|
The reason Rust has two ways to reference an element is so that you can choose
|
||||||
how the program behaves when you try to use an index value that the vector
|
how the program behaves when you try to use an index value that the vector
|
||||||
doesn't have an element for. As an example, what should a program do if it has
|
doesn’t have an element for. As an example, what should a program do if it has
|
||||||
a vector that holds five elements then tries to access an element at index 100
|
a vector that holds five elements then tries to access an element at index 100
|
||||||
like this:
|
like this:
|
||||||
|
|
||||||
@@ -142,12 +144,12 @@ element past the end of the vector to be a fatal error that should crash the
|
|||||||
program.
|
program.
|
||||||
|
|
||||||
When the `get` method is passed an index that is outside the array, it will
|
When the `get` method is passed an index that is outside the array, it will
|
||||||
return `None` without `panic!`ing. You would use this if accessing an element
|
return `None` without panicking. You would use this if accessing an element
|
||||||
beyond the range of the vector will happen occasionally under normal
|
beyond the range of the vector will happen occasionally under normal
|
||||||
circumstances. Your code can then have logic to handle having either
|
circumstances. Your code can then have logic to handle having either
|
||||||
`Some(&element)` or `None`, as we discussed in Chapter 6. For example, the
|
`Some(&element)` or `None`, as we discussed in Chapter 6. For example, the
|
||||||
index could be coming from a person entering a number. If they accidentally
|
index could be coming from a person entering a number. If they accidentally
|
||||||
enter a number that's too large and your program gets a `None` value, you could
|
enter a number that’s too large and your program gets a `None` value, you could
|
||||||
tell the user how many items are in the current `Vec` and give them another
|
tell the user how many items are in the current `Vec` and give them another
|
||||||
chance to enter a valid value. That would be more user-friendly than crashing
|
chance to enter a valid value. That would be more user-friendly than crashing
|
||||||
the program for a typo!
|
the program for a typo!
|
||||||
@@ -157,7 +159,7 @@ the program for a typo!
|
|||||||
Once the program has a valid reference, the borrow checker will enforce the
|
Once the program has a valid reference, the borrow checker will enforce the
|
||||||
ownership and borrowing rules covered in Chapter 4 to ensure this reference and
|
ownership and borrowing rules covered in Chapter 4 to ensure this reference and
|
||||||
any other references to the contents of the vector stay valid. Recall the rule
|
any other references to the contents of the vector stay valid. Recall the rule
|
||||||
that says we can't have mutable and immutable references in the same scope.
|
that says we can’t have mutable and immutable references in the same scope.
|
||||||
That rule applies in this example, where we hold an immutable reference to the
|
That rule applies in this example, where we hold an immutable reference to the
|
||||||
first element in a vector and try to add an element to the end:
|
first element in a vector and try to add an element to the end:
|
||||||
|
|
||||||
@@ -171,8 +173,9 @@ v.push(6);
|
|||||||
|
|
||||||
Compiling this will give us this error:
|
Compiling this will give us this error:
|
||||||
|
|
||||||
```text
|
```
|
||||||
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
|
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as
|
||||||
|
immutable
|
||||||
|
|
|
|
||||||
4 | let first = &v[0];
|
4 | let first = &v[0];
|
||||||
| - immutable borrow occurs here
|
| - immutable borrow occurs here
|
||||||
@@ -185,26 +188,26 @@ error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immuta
|
|||||||
|
|
||||||
This code might look like it should work: why should a reference to the first
|
This code might look like it should work: why should a reference to the first
|
||||||
element care about what changes about the end of the vector? The reason why
|
element care about what changes about the end of the vector? The reason why
|
||||||
this code isn't allowed is due to the way vectors work. Adding a new element
|
this code isn’t allowed is due to the way vectors work. Adding a new element
|
||||||
onto the end of the vector might require allocating new memory and copying the
|
onto the end of the vector might require allocating new memory and copying the
|
||||||
old elements over to the new space, in the circumstance that there isn't enough
|
old elements over to the new space, in the circumstance that there isn’t enough
|
||||||
room to put all the elements next to each other where the vector was. In that
|
room to put all the elements next to each other where the vector was. In that
|
||||||
case, the reference to the first element would be pointing to deallocated
|
case, the reference to the first element would be pointing to deallocated
|
||||||
memory. The borrowing rules prevent programs from ending up in that situation.
|
memory. The borrowing rules prevent programs from ending up in that situation.
|
||||||
|
|
||||||
> Note: For more on this, see The Nomicon at *https://doc.rust-lang.org/stable/nomicon/vec.html*.
|
> Note: For more on this, see The Nomicon at
|
||||||
|
*https://doc.rust-lang.org/stable/nomicon/vec.html*.
|
||||||
|
|
||||||
### Using an Enum to Store Multiple Types
|
### Using an Enum to Store Multiple Types
|
||||||
|
|
||||||
At the beginning of this chapter, we said that vectors can only store values
|
At the beginning of this chapter, we said that vectors can only store values
|
||||||
that are all the same type. This can be inconvenient; there are definitely use
|
that are all the same type. This can be inconvenient; there are definitely use
|
||||||
cases for needing to store a list of things of different types. Luckily, the
|
cases for needing to store a list of things of different types. Luckily, the
|
||||||
variants of an enum are all defined under the same enum type. When we need to
|
variants of an enum are all defined under the same enum type, so when we need
|
||||||
store elements of a different type in a vector this scenario, we can define and
|
to store elements of a different type in a vector, we can define and use an
|
||||||
use an enum!
|
enum!
|
||||||
|
|
||||||
For example, let's say we want to get values from a row in a spreadsheet, where
|
For example, let’s say we want to get values from a row in a spreadsheet, where
|
||||||
some of the columns in the row contain integers, some floating point numbers,
|
some of the columns in the row contain integers, some floating point numbers,
|
||||||
and some strings. We can define an enum whose variants will hold the different
|
and some strings. We can define an enum whose variants will hold the different
|
||||||
value types, and then all of the enum variants will be considered the same
|
value types, and then all of the enum variants will be considered the same
|
||||||
@@ -234,50 +237,31 @@ cause errors with the operations performed on the elements of the vector. Using
|
|||||||
an enum plus a `match` means that Rust will ensure at compile time that we
|
an enum plus a `match` means that Rust will ensure at compile time that we
|
||||||
always handle every possible case, as we discussed in Chapter 6.
|
always handle every possible case, as we discussed in Chapter 6.
|
||||||
|
|
||||||
<!-- Can you briefly explain what the match is doing here, as a recap? How does
|
If you don’t know at the time that you’re writing a program the exhaustive set
|
||||||
it mean we always handle every possible case? I'm not sure it's totally clear.
|
|
||||||
-->
|
|
||||||
<!-- Because this is a focus of chapter 6 rather than this chapter's focus, we
|
|
||||||
don't think we should repeat it here as well, but we added a reference. /Carol
|
|
||||||
-->
|
|
||||||
|
|
||||||
If you don't know at the time that you're writing a program the exhaustive set
|
|
||||||
of types the program will get at runtime to store in a vector, the enum
|
of types the program will get at runtime to store in a vector, the enum
|
||||||
technique won't work. Insetad, you can use a trait object, which we'll cover in
|
technique won’t work. Instead, you can use a trait object, which we’ll cover in
|
||||||
Chapter 13.
|
Chapter 17.
|
||||||
|
|
||||||
Now that we've gone over some of the most common ways to use vectors, be sure
|
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 all of the many useful methods
|
to take a look at the API documentation for all of the many useful methods
|
||||||
defined on `Vec` by the standard library. For example, in addition to `push`
|
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
|
there’s a `pop` method that will remove and return the last element. Let’s move
|
||||||
on to the next collection type: `String`!
|
on to the next collection type: `String`!
|
||||||
|
|
||||||
<!-- Do you mean the Rust online documentation here? Are you not including it
|
|
||||||
in the book for space reasons? We might want to justify sending them out of the
|
|
||||||
book if we don't want to cover it here -->
|
|
||||||
|
|
||||||
<!-- Yes, there are many, many methods on Vec: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html
|
|
||||||
Also there are occcasionally new methods available with new versions of the
|
|
||||||
language, so there's no way we can be comprehensive here. We want the reader to
|
|
||||||
use the API documentation in these situations since the purpose of the online
|
|
||||||
docs is to be comprehensive and up to date. I personally wouldn't expect a book
|
|
||||||
like this to duplicate the info that's in the API docs, so I don't think a
|
|
||||||
justification is necessary here. /Carol -->
|
|
||||||
|
|
||||||
## Strings
|
## Strings
|
||||||
|
|
||||||
We've already talked about strings a bunch in Chapter 4, but let's take a more
|
We’ve already talked about strings a bunch in Chapter 4, but let’s take a more
|
||||||
in-depth look at them now. Strings are an area that new Rustaceans commonly get
|
in-depth look at them now. Strings are an area that new Rustaceans commonly get
|
||||||
stuck on. This is due to a combination of three things: Rust's propensity for
|
stuck on. 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
|
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
|
structure than many programmers give them credit for, and UTF-8. These things
|
||||||
combine in a way that can seem difficult when coming from other languages.
|
combine in a way that can seem difficult when coming from other languages.
|
||||||
|
|
||||||
The reason Strings are in the collections chapter is that strings are
|
The reason strings are in the collections chapter is that strings are
|
||||||
implemented as a collection of bytes plus some methods to provide useful
|
implemented as a collection of bytes plus some methods to provide useful
|
||||||
functionality when those bytes are interpreted as text. In this section, we'll
|
functionality when those bytes are interpreted as text. In this section, we’ll
|
||||||
talk about the operations on `String` that every collection type has, like
|
talk about the operations on `String` that every collection type has, like
|
||||||
creating, updating, and reading. We'll also discuss the ways in which `String`
|
creating, updating, and reading. We’ll also discuss the ways in which `String`
|
||||||
is different than the other collections, namely how indexing into a `String` is
|
is different than the other collections, namely how indexing into a `String` is
|
||||||
complicated by the differences in which people and computers interpret `String`
|
complicated by the differences in which people and computers interpret `String`
|
||||||
data.
|
data.
|
||||||
@@ -285,26 +269,26 @@ data.
|
|||||||
### What is a String?
|
### What is a String?
|
||||||
|
|
||||||
Before we can dig into those aspects, we need to talk about what exactly we
|
Before we can dig into those aspects, we need to talk about what exactly we
|
||||||
mean by the term 'string'. Rust actually only has one string type in the core
|
mean by the term *string*. Rust actually only has one string type in the core
|
||||||
language itself: `str`, the string slice, which is usually seen in its borrowed
|
language itself: `str`, the string slice, which is usually seen in its borrowed
|
||||||
form, `&str`. We talked about *string slices* in Chapter 4: these are a
|
form, `&str`. We talked about *string slices* in Chapter 4: these are a
|
||||||
reference to some UTF-8 encoded string data stored elsewhere. String literals,
|
reference to some UTF-8 encoded string data stored elsewhere. String literals,
|
||||||
for example, are stored in the binary output of the program, and are therefore
|
for example, are stored in the binary output of the program, and are therefore
|
||||||
string slices.
|
string slices.
|
||||||
|
|
||||||
The type called `String` is provided in Rust's standard library rather than
|
The type called `String` is provided in Rust’s standard library rather than
|
||||||
coded into the core language, and is a growable, mutable, owned, UTF-8 encoded
|
coded into the core language, and is a growable, mutable, owned, UTF-8 encoded
|
||||||
string type. When Rustaceans talk about 'strings' in Rust, they usually mean
|
string type. When Rustaceans talk about “strings” in Rust, they usually mean
|
||||||
both the `String` and the string slice `&str` types, not just one of those.
|
both the `String` and the string slice `&str` types, not just one of those.
|
||||||
This section is largely about `String`, but both these types are used heavily
|
This section is largely about `String`, but both these types are used heavily
|
||||||
in Rust's standard library. Both `String` and string slices are UTF-8 encoded.
|
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
|
Rust’s standard library also includes a number of other string types, such as
|
||||||
`OsString`, `OsStr`, `CString`, and `CStr`. Library crates may provide even
|
`OsString`, `OsStr`, `CString`, and `CStr`. Library crates may provide even
|
||||||
more options for storing string data. Similar to the `*String`/`*Str` naming,
|
more options for storing string data. Similar to the `*String`/`*Str` naming,
|
||||||
they often provide an owned and borrowed variant, just like `String`/`&str`.
|
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
|
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
|
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
|
types in this chapter; see their API documentation for more about how to use
|
||||||
them and when each is appropriate.
|
them and when each is appropriate.
|
||||||
|
|
||||||
@@ -319,7 +303,7 @@ let s = String::new();
|
|||||||
|
|
||||||
This creates a new empty string called `s` that we can then load data into.
|
This creates a new empty string called `s` that we can then load data into.
|
||||||
|
|
||||||
Often, we'll have some initial data that we'd like to start the string off
|
Often, we’ll have some initial data that we’d like to start the string off
|
||||||
with. For that, we use the `to_string` method, which is available on any type
|
with. For that, we use the `to_string` method, which is available on any type
|
||||||
that implements the `Display` trait, which string literals do:
|
that implements the `Display` trait, which string literals do:
|
||||||
|
|
||||||
@@ -366,8 +350,8 @@ let hello = "Hola";
|
|||||||
|
|
||||||
### Updating a String
|
### Updating a String
|
||||||
|
|
||||||
A `String` can can grow in size and its contents can change just like the
|
A `String` can grow in size and its contents can change just like the contents
|
||||||
contents of a `Vec`, by pushing more data into it. In addition, `String` has
|
of a `Vec`, by pushing more data into it. In addition, `String` has
|
||||||
concatenation operations implemented with the `+` operator for convenience.
|
concatenation operations implemented with the `+` operator for convenience.
|
||||||
|
|
||||||
#### Appending to a String with Push
|
#### Appending to a String with Push
|
||||||
@@ -379,9 +363,9 @@ let mut s = String::from("foo");
|
|||||||
s.push_str("bar");
|
s.push_str("bar");
|
||||||
```
|
```
|
||||||
|
|
||||||
`s` will contain "foobar" after these two lines. The `push_str` method takes a
|
`s` will contain “foobar” after these two lines. The `push_str` method takes a
|
||||||
string slice because we don't necessarily want to take ownership of the
|
string slice because we don’t necessarily want to take ownership of the
|
||||||
argument. For example, it would be unfortunate if we weren't able to use `s2`
|
parameter. For example, it would be unfortunate if we weren’t able to use `s2`
|
||||||
after appending its contents to `s1`:
|
after appending its contents to `s1`:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -390,7 +374,7 @@ let s2 = String::from("bar");
|
|||||||
s1.push_str(&s2);
|
s1.push_str(&s2);
|
||||||
```
|
```
|
||||||
|
|
||||||
The `push` method is defined to take a single character as an argument and add
|
The `push` method is defined to have a single character as a parameter and add
|
||||||
it to the `String`:
|
it to the `String`:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -398,11 +382,11 @@ let mut s = String::from("lo");
|
|||||||
s.push('l');
|
s.push('l');
|
||||||
```
|
```
|
||||||
|
|
||||||
After this, `s` will contain "lol".
|
After this, `s` will contain “lol”.
|
||||||
|
|
||||||
#### Concatenation with the + Operator or the `format!` Macro
|
#### Concatenation with the + Operator or the `format!` Macro
|
||||||
|
|
||||||
Often, we'll want to combine two existing strings together. One way is to use
|
Often, we’ll want to combine two existing strings together. One way is to use
|
||||||
the `+` operator like this:
|
the `+` operator like this:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -417,31 +401,32 @@ reference to `s2` has to do with the signature of the method that gets called
|
|||||||
when we use the `+` operator. The `+` operator uses the `add` method, whose
|
when we use the `+` operator. The `+` operator uses the `add` method, whose
|
||||||
signature looks something like this:
|
signature looks something like this:
|
||||||
|
|
||||||
```rust,ignore
|
```
|
||||||
fn add(self, s: &str) -> String {
|
fn add(self, s: &str) -> String {
|
||||||
```
|
```
|
||||||
|
|
||||||
This isn't the exact signature that's in the standard library; there `add` is
|
This isn’t the exact signature that’s in the standard library; there `add` is
|
||||||
defined using generics. Here, we're looking at the signature of `add` with
|
defined using generics. Here, we’re looking at the signature of `add` with
|
||||||
concrete types substituted for the generic ones, which is what happens when we
|
concrete types substituted for the generic ones, which is what happens when we
|
||||||
call this method with `String` values. This signature gives us the clues we
|
call this method with `String` values. We'll be discussing generics in Chapter
|
||||||
need to understand the tricky bits of the `+` operator.
|
10. This signature gives us the clues we need to understand the tricky bits of
|
||||||
|
the `+` operator.
|
||||||
|
|
||||||
First of all, `s2` has an `&`, meaning that we are adding a *reference* of the
|
First of all, `s2` has an `&`, meaning that we are adding a *reference* of the
|
||||||
second string to the first string. This is because of the `s` argument in the
|
second string to the first string. This is because of the `s` parameter in the
|
||||||
`add` function: we can only add a `&str` to a `String`, we can't add two
|
`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` values together. Remember back in Chapter 4 when we talked about how
|
||||||
`&String` will coerce to `&str`: we write `&s2` so that the `String` will
|
`&String` will coerce to `&str`: we write `&s2` so that the `String` will
|
||||||
coerce to the proper type, `&str`. Because this method does not take ownership
|
coerce to the proper type, `&str`. Because this method does not take ownership
|
||||||
of the argument, `s2` will still be valid after this operation.
|
of the parameter, `s2` will still be valid after this operation.
|
||||||
|
|
||||||
Second, we can see in the signature that `add` takes ownership of `self`,
|
Second, we can see in the signature that `add` takes ownership of `self`,
|
||||||
because `self` does *not* have an `&`. This means `s1` in the above example
|
because `self` does *not* have an `&`. This means `s1` in the above example
|
||||||
will be moved into the `add` call and no longer be valid after that. So while
|
will be moved into the `add` call and no longer be valid after that. So while
|
||||||
`let s3 = s1 + &s2;` looks like it will copy both strings and create a new one,
|
`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
|
this statement actually takes ownership of `s1`, appends a copy of the contents
|
||||||
contents, then returns ownership of the result. In other words, it looks like
|
of `s2`, 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
|
it’s making a lot of copies, but isn’t: the implementation is more efficient
|
||||||
than copying.
|
than copying.
|
||||||
|
|
||||||
If we need to concatenate multiple strings, the behavior of `+` gets unwieldy:
|
If we need to concatenate multiple strings, the behavior of `+` gets unwieldy:
|
||||||
@@ -454,8 +439,8 @@ let s3 = String::from("toe");
|
|||||||
let s = s1 + "-" + &s2 + "-" + &s3;
|
let s = s1 + "-" + &s2 + "-" + &s3;
|
||||||
```
|
```
|
||||||
|
|
||||||
`s` will be "tic-tac-toe" at this point. With all of the `+` and `"`
|
`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
|
characters, it gets hard to see what’s going on. For more complicated string
|
||||||
combining, we can use the `format!` macro:
|
combining, we can use the `format!` macro:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -466,31 +451,16 @@ let s3 = String::from("toe");
|
|||||||
let s = format!("{}-{}-{}", s1, s2, s3);
|
let s = format!("{}-{}-{}", s1, s2, s3);
|
||||||
```
|
```
|
||||||
|
|
||||||
<!-- Are we going to discuss the format macro elsewhere at all? If not, some
|
This code will also set `s` to “tic-tac-toe”. The `format!` macro works in the
|
||||||
more info here might be good, this seems like a really useful tool. Is it only
|
|
||||||
used on strings? -->
|
|
||||||
|
|
||||||
<!-- No, we weren't planning on it. We thought it would be sufficient to
|
|
||||||
mention that it works the same way as `println!` since we've covered how
|
|
||||||
`println!` works in Ch 2, "Printing Values with `println!` Placeholders" and Ch
|
|
||||||
5, Ch 5, "Adding Useful Functionality with Derived Traits". `format!` can be
|
|
||||||
used on anything that `println!` can; using `{}` in the format string works
|
|
||||||
with anything that implements the `Display` trait and `{:?}` works with
|
|
||||||
anything that implements the `Debug` trait. Do you have any thoughts on how we
|
|
||||||
could make the similarities with `format!` and `println!` clearer than what we
|
|
||||||
have in the next paragraph without repeating the `println!` content too much?
|
|
||||||
/Carol -->
|
|
||||||
|
|
||||||
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
|
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, and
|
returns a `String` with the contents. This version is much easier to read, and
|
||||||
also does not take ownership of any of its arguments.
|
also does not take ownership of any of its parameters.
|
||||||
|
|
||||||
### Indexing into Strings
|
### Indexing into Strings
|
||||||
|
|
||||||
In many other languages, accessing individual characters in a string by
|
In many other languages, accessing individual characters in a string by
|
||||||
referencing them by index is a valid and common operation. In Rust, however, if
|
referencing them 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.
|
we try to access parts of a `String` using indexing syntax, we’ll get an error.
|
||||||
That is, this code:
|
That is, this code:
|
||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
@@ -509,31 +479,32 @@ satisfied [--explain E0277]
|
|||||||
note: the type `std::string::String` cannot be indexed by `_`
|
note: the type `std::string::String` cannot be indexed by `_`
|
||||||
```
|
```
|
||||||
|
|
||||||
The error and the note tell the story: Rust strings don't support indexing. 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
|
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.
|
bit about how Rust stores strings in memory.
|
||||||
|
|
||||||
#### Internal Representation
|
#### Internal Representation
|
||||||
|
|
||||||
A `String` is a wrapper over a `Vec<u8>`. Let's take a look at some of our
|
A `String` is a wrapper over a `Vec<u8>`. Let’s take a look at some of our
|
||||||
properly-encoded UTF-8 example strings from before. First, this one:
|
properly-encoded UTF-8 example strings from before. First, this one:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
let len = "Hola".len();
|
let len = String::from("Hola").len();
|
||||||
```
|
```
|
||||||
|
|
||||||
In this case, `len` will be four, which means the `Vec` storing the string
|
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
|
“Hola” is four bytes long: each of these letters takes one byte when encoded in
|
||||||
UTF-8. What about this example, though?
|
UTF-8. What about this example, though?
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
let len = "Здравствуйте".len();
|
let len = String::from("Здравствуйте").len();
|
||||||
```
|
```
|
||||||
|
|
||||||
A person asked how long the string is might say 12. However, Rust's answer
|
A person asked how long the string is might say 12. However, Rust’s answer is
|
||||||
is 24. This is the number of bytes that it takes to encode "Здравствуйте" in
|
24. This is the number of bytes that it takes to encode “Здравствуйте” in
|
||||||
UTF-8, since each character takes two bytes of storage. Therefore, an index
|
UTF-8, since each Unicode scalar value takes two bytes of storage. Therefore,
|
||||||
into the string's bytes will not always correlate to a valid character.
|
an index into the string’s bytes will not always correlate to a valid Unicode
|
||||||
|
scalar value.
|
||||||
|
|
||||||
To demonstrate, consider this invalid Rust code:
|
To demonstrate, consider this invalid Rust code:
|
||||||
|
|
||||||
@@ -546,9 +517,9 @@ What should the value of `answer` be? Should it be `З`, the first letter? When
|
|||||||
encoded in UTF-8, the first byte of `З` is `208`, and the second is `151`, so
|
encoded in UTF-8, the first byte of `З` is `208`, and the second is `151`, so
|
||||||
`answer` should in fact be `208`, but `208` is not a valid character on its
|
`answer` should in fact be `208`, but `208` is not a valid character on its
|
||||||
own. Returning `208` is likely not what a person would want if they asked for
|
own. Returning `208` is likely not what a person would want if they asked for
|
||||||
the first letter of this string, but that's the only data that Rust has at byte
|
the first letter of this string, but that’s the only data that Rust has at byte
|
||||||
index 0. Returning the byte value is probably not what people want, even with
|
index 0. Returning the byte value is probably not what people want, even with
|
||||||
only latin letters: `&"hello"[0]` would return `104`, not `h`. To avoid
|
only Latin letters: `&"hello"[0]` would return `104`, not `h`. To avoid
|
||||||
returning an unexpected value and causing bugs that might not be discovered
|
returning an unexpected value and causing bugs that might not be discovered
|
||||||
immediately, Rust chooses to not compile this code at all and prevent
|
immediately, Rust chooses to not compile this code at all and prevent
|
||||||
misunderstandings earlier.
|
misunderstandings earlier.
|
||||||
@@ -556,18 +527,19 @@ misunderstandings earlier.
|
|||||||
#### 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
|
This leads to another point about UTF-8: there are really three relevant ways
|
||||||
to look at strings, from Rust's perspective: as bytes, scalar values, and
|
to look at strings, from Rust’s perspective: as bytes, scalar values, and
|
||||||
grapheme clusters (the closest thing to what people would call 'letters').
|
grapheme clusters (the closest thing to what people would call *letters*).
|
||||||
|
|
||||||
If we look at the Hindi word "नमस्ते" written in the Devanagari script, it is
|
If we look at the Hindi word “नमस्ते” written in the Devanagari script, it is
|
||||||
ultimately stored as a `Vec` of `u8` values that looks like this:
|
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]
|
[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164,
|
||||||
|
224, 165, 135]
|
||||||
```
|
```
|
||||||
|
|
||||||
That's 18 bytes, and is how computers ultimately store this data. If we look at
|
That’s 18 bytes, and is how computers ultimately store this data. If we look at
|
||||||
them as Unicode scalar values, which are what Rust's `char` type is, those
|
them as Unicode scalar values, which are what Rust’s `char` type is, those
|
||||||
bytes look like this:
|
bytes look like this:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@@ -575,8 +547,8 @@ bytes look like this:
|
|||||||
```
|
```
|
||||||
|
|
||||||
There are six `char` values here, but the fourth and sixth are not letters,
|
There are six `char` values here, but the fourth and sixth are not letters,
|
||||||
they're diacritics that don't make sense on their own. Finally, if we look at
|
they’re diacritics that don’t make sense on their own. Finally, if we look at
|
||||||
them as grapheme clusters, we'd get what a person would call the four letters
|
them as grapheme clusters, we’d get what a person would call the four letters
|
||||||
that make up this word:
|
that make up this word:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@@ -589,18 +561,17 @@ what human language the data is in.
|
|||||||
|
|
||||||
A final reason Rust does not allow you to index into a `String` to get a
|
A final reason Rust does not allow you to index into a `String` to get a
|
||||||
character is that indexing operations are expected to always take constant time
|
character is that indexing operations are expected to always take constant time
|
||||||
(O(1)). It isn't possible to guarantee that performance with a `String`,
|
(O(1)). It isn’t possible to guarantee that performance with a `String`,
|
||||||
though, since Rust would have to walk through the contents from the beginning
|
though, since Rust would have to walk through the contents from the beginning
|
||||||
to the index to determine how many valid characters there were.
|
to the index to determine how many valid characters there were.
|
||||||
|
|
||||||
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
|
Because it's not clear what the return type of string indexing should be, and
|
||||||
to be fast. While we can't use `[]` with a single number, we _can_ use `[]`
|
it is often a bad idea to index into a string, Rust dissuades you from doing so
|
||||||
with a range to create a string slice containing particular bytes:
|
by asking you to be more specific if you really need it. The way you can be
|
||||||
|
more specific than indexing using `[]` with a single number is using `[]` with
|
||||||
|
a range to create a string slice containing particular bytes:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
let hello = "Здравствуйте";
|
let hello = "Здравствуйте";
|
||||||
@@ -610,7 +581,7 @@ let s = &hello[0..4];
|
|||||||
|
|
||||||
Here, `s` will be a `&str` that contains the first four bytes of the string.
|
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
|
Earlier, we mentioned that each of these characters was two bytes, so that
|
||||||
means that `s` will be "Зд".
|
means that `s` will be “Зд”.
|
||||||
|
|
||||||
What would happen if we did `&hello[0..1]`? The answer: it will panic at
|
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:
|
runtime, in the same way that accessing an invalid index in a vector does:
|
||||||
@@ -626,10 +597,10 @@ You should use this with caution, since it can cause your program to crash.
|
|||||||
|
|
||||||
Luckily, there are other ways we can access elements in a String.
|
Luckily, there are other ways we can access elements in a String.
|
||||||
|
|
||||||
If we need to perform operations on individual characters, the best way to do
|
If we need to perform operations on individual Unicode scalar values, the best
|
||||||
so is to use the `chars` method. Calling `chars` on "नमस्ते" separates out and
|
way to do so is to use the `chars` method. Calling `chars` on “नमस्ते”
|
||||||
returns six values of type `char`, and you can iterate over the result in order
|
separates out and returns six values of type `char`, and you can iterate over
|
||||||
to access each element:
|
the result in order to access each element:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
for c in "नमस्ते".chars() {
|
for c in "नमस्ते".chars() {
|
||||||
@@ -667,20 +638,12 @@ This code will print the 18 bytes that make up this `String`, starting with:
|
|||||||
// ... etc
|
// ... etc
|
||||||
```
|
```
|
||||||
|
|
||||||
But make sure to remember that valid UTF-8 characters may be made up of more
|
But make sure to remember that valid Unicode scalar values may be made up of
|
||||||
than one byte.
|
more than one byte.
|
||||||
|
|
||||||
Getting grapheme clusters from `String`s is complex, so this functionality is
|
Getting grapheme clusters from strings is complex, so this functionality is not
|
||||||
not provided by the standard library. There are crates available on crates.io
|
provided by the standard library. There are crates available on crates.io if
|
||||||
if this is the functionality you need.
|
this is the functionality you need.
|
||||||
|
|
||||||
<!-- Can you recommend some, or maybe just say why we aren't outlining the
|
|
||||||
method here, ie it's complicated and therefore best to use a crate? -->
|
|
||||||
|
|
||||||
<!-- We're trying not to mention too many crates in the book. Most crates are
|
|
||||||
provided by the community, so we don't want to mention some and not others and
|
|
||||||
seem biased towards certain crates, plus crates can change more quickly (and
|
|
||||||
new crates can be created) than the language and this book will. /Carol -->
|
|
||||||
|
|
||||||
### Strings are Not so Simple
|
### Strings are Not so Simple
|
||||||
|
|
||||||
@@ -693,24 +656,24 @@ of strings than other programming languages do, but this will prevent you from
|
|||||||
having to handle errors involving non-ASCII characters later in your
|
having to handle errors involving non-ASCII characters later in your
|
||||||
development lifecycle.
|
development lifecycle.
|
||||||
|
|
||||||
Let's switch to something a bit less complex: Hash Map!
|
Let’s switch to something a bit less complex: hash map!
|
||||||
|
|
||||||
## Hash Maps
|
## Hash Maps
|
||||||
|
|
||||||
The last of our fundamental collections is the *hash map*. The type `HashMap<K,
|
The last of our common collections is the *hash map*. The type `HashMap<K, V>`
|
||||||
V>` stores a mapping of keys of type `K` to values of type `V`. It does this
|
stores a mapping of keys of type `K` to values of type `V`. It does this via a
|
||||||
via a *hashing function*, which determines how it places these keys and values
|
*hashing function*, which determines how it places these keys and values into
|
||||||
into memory. Many different programming languages support this kind of data
|
memory. Many different programming languages support this kind of data
|
||||||
structure, but often with a different name: hash, map, object, hash table, or
|
structure, but often with a different name: hash, map, object, hash table, or
|
||||||
associative array, just to name a few.
|
associative array, just to name a few.
|
||||||
|
|
||||||
Hash maps are useful for when you want to be able to look up data not by an
|
Hash maps are useful for when you want to be able to look up data not by an
|
||||||
index, as you can with vectors, but by using a key that can be of any type. For
|
index, as you can with vectors, but by using a key that can be of any type. For
|
||||||
example, in a game, you could keep track of each team's score in a hash map
|
example, in a game, you could keep track of each team’s score in a hash map
|
||||||
where each key is a team's name and the values are each team's score. Given a
|
where each key is a team’s name and the values are each team’s score. Given a
|
||||||
team name, you can retrieve their score.
|
team name, you can retrieve their score.
|
||||||
|
|
||||||
We'll go over the basic API of hash maps in this chapter, but there are many
|
We’ll go over the basic API of hash maps in this chapter, but there are many
|
||||||
more goodies hiding in the functions defined on `HashMap` by the standard
|
more goodies hiding in the functions defined on `HashMap` by the standard
|
||||||
library. As always, check the standard library documentation for more
|
library. As always, check the standard library documentation for more
|
||||||
information.
|
information.
|
||||||
@@ -718,7 +681,7 @@ information.
|
|||||||
### Creating a New Hash Map
|
### 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`.
|
||||||
Here we're keeping track of the scores of two teams whose names are Blue and
|
Here we’re keeping track of the scores of two teams whose names are Blue and
|
||||||
Yellow. The Blue team will start with 10 points and the Yellow team starts with
|
Yellow. The Blue team will start with 10 points and the Yellow team starts with
|
||||||
50:
|
50:
|
||||||
|
|
||||||
@@ -732,22 +695,22 @@ scores.insert(String::from("Yellow"), 50);
|
|||||||
```
|
```
|
||||||
|
|
||||||
Note that we need to first `use` the `HashMap` from the collections portion of
|
Note that we need to first `use` the `HashMap` from the collections portion of
|
||||||
the standard library. Of our three fundamental collections, this one is the
|
the standard library. Of our three common collections, this one is the least
|
||||||
least often used, so it's not included in the features imported automatically
|
often used, so it’s not included in the features imported automatically in the
|
||||||
in the prelude. Hash maps also have less support from the standard library;
|
prelude. Hash maps also have less support from the standard library; there’s no
|
||||||
there's no built-in macro to construct them, for example.
|
built-in macro to construct them, for example.
|
||||||
|
|
||||||
Just like vectors, hash maps store their data on the heap. This `HashMap` has
|
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
|
keys of type `String` and values of type `i32`. Like vectors, hash maps are
|
||||||
homogenous: all of the keys must have the same type, and all of the values must
|
homogeneous: all of the keys must have the same type, and all of the values
|
||||||
have the same type.
|
must have the same type.
|
||||||
|
|
||||||
Another way of constructing a hash map is by using the `collect` method on a
|
Another way of constructing a hash map is by using the `collect` method on a
|
||||||
vector of tuples, where each tuple consists of a key and its value. The
|
vector of tuples, where each tuple consists of a key and its value. The
|
||||||
`collect` method gathers up data into a number of collection types, including
|
`collect` method gathers up data into a number of collection types, including
|
||||||
`HashMap`. For example, if we had the team names and initial scores in two
|
`HashMap`. For example, if we had the team names and initial scores in two
|
||||||
separate vectors, we can use the `zip` method to create a vector of tuples
|
separate vectors, we can use the `zip` method to create a vector of tuples
|
||||||
where "Blue" is paired with 10, and so forth. Then we can use the `collect`
|
where “Blue” is paired with 10, and so forth. Then we can use the `collect`
|
||||||
method to turn that vector of tuples into a `HashMap`:
|
method to turn that vector of tuples into a `HashMap`:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -759,13 +722,13 @@ let initial_scores = vec![10, 50];
|
|||||||
let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect();
|
let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect();
|
||||||
```
|
```
|
||||||
|
|
||||||
The type annotation `HashMap<_, _>` is needed here because it's possible to
|
The type annotation `HashMap<_, _>` is needed here because it’s possible to
|
||||||
`collect` into many different data structures, and Rust doesn't know which you
|
`collect` into many different data structures, and Rust doesn’t know which you
|
||||||
want unless you specify. For the type parameters for the key and value types,
|
want unless you specify. For the type parameters for the key and value types,
|
||||||
however, we use underscores and Rust can infer the types that the hash map
|
however, we use underscores and Rust can infer the types that the hash map
|
||||||
contains based on the types of the data in the vector.
|
contains based on the types of the data in the vector.
|
||||||
|
|
||||||
### Hashmaps and Ownership
|
### Hash Maps and Ownership
|
||||||
|
|
||||||
For types that implement the `Copy` trait, like `i32`, the values are copied
|
For types that implement the `Copy` trait, like `i32`, the values are copied
|
||||||
into the hash map. For owned values like `String`, the values will be moved and
|
into the hash map. For owned values like `String`, the values will be moved and
|
||||||
@@ -806,11 +769,11 @@ let team_name = String::from("Blue");
|
|||||||
let score = scores.get(&team_name);
|
let score = scores.get(&team_name);
|
||||||
```
|
```
|
||||||
|
|
||||||
Here, `score` will have the value that's associated with the Blue team, and the
|
Here, `score` will have the value that’s associated with the Blue team, and the
|
||||||
result will be `Some(10)`. The result is wrapped in `Some` because `get`
|
result will be `Some(10)`. The result is wrapped in `Some` because `get`
|
||||||
returns an `Option<V>`; if there's no value for that key in the hash map, `get`
|
returns an `Option<V>`; if there’s no value for that key in the hash map, `get`
|
||||||
will return `None`. The program will need to handle the `Option` in one of
|
will return `None`. The program will need to handle the `Option` in one of the
|
||||||
the ways that we covered in Chapter 6.
|
ways that we covered in Chapter 6.
|
||||||
|
|
||||||
We can iterate over each key/value pair in a hash map 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:
|
do with vectors, using a `for` loop:
|
||||||
@@ -837,26 +800,21 @@ Blue: 10
|
|||||||
|
|
||||||
### Updating a Hash Map
|
### Updating a Hash Map
|
||||||
|
|
||||||
<!-- So the quantity of keys must be defined up front, that's not growable?
|
|
||||||
That could be worthy saying -->
|
|
||||||
<!-- No, the number of keys is growable, it's just that for EACH individual
|
|
||||||
key, there can only be one value. I've tried to clarify. /Carol -->
|
|
||||||
|
|
||||||
While the number of keys and values is growable, each individual key can only
|
While the number of keys and values is growable, each individual key can only
|
||||||
have one value associated with it at a time. When we want to change the data in
|
have one value associated with it at a time. 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
|
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,
|
value assigned. We could choose to replace the old value with the new value,
|
||||||
completely disregarding the old value. We could choose to keep the old value
|
completely disregarding the old 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*
|
and ignore the new value, and only add the new value if the key *doesn’t*
|
||||||
already have a value. Or we could combine the old value and the new value.
|
already have a value. Or we could combine the old value and the new value.
|
||||||
Let's look at how to do each of these!
|
Let’s look at how to do each of these!
|
||||||
|
|
||||||
#### Overwriting a Value
|
#### Overwriting a Value
|
||||||
|
|
||||||
If we insert a key and a value into a hashmap, then insert that same key with a
|
If we insert a key and a value into a hash map, then insert that same key with
|
||||||
different value, the value associated with that key will be replaced. Even
|
a different value, the value associated with that key will be replaced. Even
|
||||||
though this following code calls `insert` twice, the hash map will only contain
|
though this following code calls `insert` twice, the hash map will only contain
|
||||||
one key/value pair because we're inserting the value for the Blue team's key
|
one key/value pair because we’re inserting the value for the Blue team’s key
|
||||||
both times:
|
both times:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -870,19 +828,18 @@ scores.insert(String::from("Blue"), 25);
|
|||||||
println!("{:?}", scores);
|
println!("{:?}", scores);
|
||||||
```
|
```
|
||||||
|
|
||||||
This will print `{"Blue": 25}`. The original value of 25 has been overwritten.
|
This will print `{"Blue": 25}`. The original value of 10 has been overwritten.
|
||||||
|
|
||||||
|
|
||||||
#### Only Insert If the Key Has No Value
|
#### Only Insert If the Key Has No Value
|
||||||
|
|
||||||
It's common to want to check if a particular key has a value and, if it does
|
It’s common to want to check if a particular key has a value and, if it does
|
||||||
not, insert a value for it. Hash maps have a special API for this, called
|
not, insert a value for it. Hash maps have a special API for this, called
|
||||||
`entry`, that takes the key we want to check as an argument. The return value
|
`entry`, that takes the key we want to check as an argument. The return value
|
||||||
of the `entry` function is an enum, `Entry`, that represents a value that might
|
of the `entry` function is an enum, `Entry`, that represents a value that might
|
||||||
or might not exist. Let's say that we want to check if the key for the Yellow
|
or might not exist. Let’s say that we want to check if the key for the Yellow
|
||||||
team has a value associated with it. If it doesn't, we want to insert the value
|
team has a value associated with it. If it doesn’t, we want to insert the value
|
||||||
50, and the same for the Blue team. With the entry API, the code for this
|
50, and the same for the Blue team. With the entry API, the code for this looks
|
||||||
looks like:
|
like:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -896,23 +853,23 @@ scores.entry(String::from("Blue")).or_insert(50);
|
|||||||
println!("{:?}", scores);
|
println!("{:?}", scores);
|
||||||
```
|
```
|
||||||
|
|
||||||
The `or_insert` method on `Entry` returns the value for the `Entry`'s key if it
|
The `or_insert` method on `Entry` returns the value for the corresponding
|
||||||
exists, and if not, inserts its argument as the new value for the `Entry`'s key
|
`Entry` key if it exists, and if not, inserts its argument as the new value for
|
||||||
and returns that. This is much cleaner than writing the logic ourselves, and in
|
this key and returns the modified `Entry`. This is much cleaner than writing
|
||||||
addition, plays more nicely with the borrow checker.
|
the logic ourselves, and in addition, plays more nicely with the borrow checker.
|
||||||
|
|
||||||
This code will print `{"Yellow": 50, "Blue": 10}`. The first call to `entry`
|
This code will print `{"Yellow": 50, "Blue": 10}`. The first call to `entry`
|
||||||
will insert the key for the Yellow team with the value 50, since the Yellow
|
will insert the key for the Yellow team with the value 50, since the Yellow
|
||||||
team doesn't have a value already. The second call to `entry` will not change
|
team doesn’t have a value already. The second call to `entry` will not change
|
||||||
the hash map since the Blue team already has the value 10.
|
the hash map since the Blue team already has the value 10.
|
||||||
|
|
||||||
#### Update a Value Based on the Old Value
|
#### Update a Value Based on the Old Value
|
||||||
|
|
||||||
Another common use case for hash maps 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, based on the old value. For instance, if we wanted to count how many times
|
it, based on the old value. For instance, if we wanted to count how many times
|
||||||
each word appeared in some text, we could use a hash map 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.
|
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`.
|
If this is the first time we’ve seen a word, we’ll first insert the value `0`.
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -944,8 +901,10 @@ hashing algorithm out there, but the tradeoff for better security that comes
|
|||||||
with the drop in performance is worth it. If you profile your code and find
|
with the drop in performance is worth it. If you profile your code and find
|
||||||
that the default hash function is too slow for your purposes, you can switch to
|
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 a type that
|
another function by specifying a different *hasher*. A hasher is a type that
|
||||||
implements the `BuildHasher` trait. We'll be talking about traits and how to
|
implements the `BuildHasher` trait. We’ll be talking about traits and how to
|
||||||
implement them in Chapter 10.
|
implement them in Chapter 10. You don't necessarily have to implement your own
|
||||||
|
hasher from scratch; crates.io has libraries that others have shared that
|
||||||
|
provide hashers implementing many common hashing algorithms.
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
@@ -953,21 +912,21 @@ Vectors, strings, and hash maps will take you far in programs where you need to
|
|||||||
store, access, and modify data. Here are some exercises you should now be
|
store, access, and modify data. Here are some exercises you should now be
|
||||||
equipped to solve:
|
equipped to solve:
|
||||||
|
|
||||||
1. Given a list of integers, use a vector and return the mean (average), median
|
* Given a list of integers, use a vector and return the mean (average), median
|
||||||
(when sorted, the value in the middle position), and mode (the value that
|
(when sorted, the value in the middle position), and mode (the value that
|
||||||
occurs most often; a hash map will be helpful here) of the list.
|
occurs most often; a hash map will be helpful here) of the list.
|
||||||
2. Convert strings to Pig Latin, where the first consonant of each word is
|
* Convert strings to Pig Latin, where the first consonant of each word is moved
|
||||||
moved to the end of the word with an added "ay", so "first" becomes
|
to the end of the word with an added “ay”, so “first” becomes “irst-fay”.
|
||||||
"irst-fay". Words that start with a vowel get "hay" added to the end instead
|
Words that start with a vowel get “hay” added to the end instead (“apple”
|
||||||
("apple" becomes "apple-hay"). Remember about UTF-8 encoding!
|
becomes “apple-hay”). Remember about UTF-8 encoding!
|
||||||
3. Using a hash map 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
|
employee names to a department in the company. For example, “Add Sally to
|
||||||
Engineering" or "Add Amir to Sales". Then let the user retrieve a list of all
|
Engineering” or “Add Amir to Sales”. Then let the user retrieve a list of all
|
||||||
people in a department or all people in the company by department, sorted
|
people in a department or all people in the company by department, sorted
|
||||||
alphabetically.
|
alphabetically.
|
||||||
|
|
||||||
The standard library API documentation describes methods these types have that
|
The standard library API documentation describes methods these types have that
|
||||||
will be helpful for these exercises!
|
will be helpful for these exercises!
|
||||||
|
|
||||||
We're getting into more complex programs where operations can fail, which means
|
We’re getting into more complex programs where operations can fail, which means
|
||||||
it's a perfect time to go over error handling next!
|
it’s a perfect time to go over error handling next!
|
||||||
|
|||||||
Binary file not shown.
+1
-1
@@ -35,7 +35,7 @@
|
|||||||
- [Controlling Visibility with `pub`](ch07-02-controlling-visibility-with-pub.md)
|
- [Controlling Visibility with `pub`](ch07-02-controlling-visibility-with-pub.md)
|
||||||
- [Importing Names with `use`](ch07-03-importing-names-with-use.md)
|
- [Importing Names with `use`](ch07-03-importing-names-with-use.md)
|
||||||
|
|
||||||
- [Fundamental Collections](ch08-00-fundamental-collections.md)
|
- [Common Collections](ch08-00-common-collections.md)
|
||||||
- [Vectors](ch08-01-vectors.md)
|
- [Vectors](ch08-01-vectors.md)
|
||||||
- [Strings](ch08-02-strings.md)
|
- [Strings](ch08-02-strings.md)
|
||||||
- [Hash Maps](ch08-03-hash-maps.md)
|
- [Hash Maps](ch08-03-hash-maps.md)
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Common Collections
|
||||||
|
|
||||||
|
Rust’s standard library includes a number of really useful data structures
|
||||||
|
called *collections*. Most other data types represent one specific value, but
|
||||||
|
collections can contain multiple values. Unlike the built-in array and tuple
|
||||||
|
types, the data these collections point to is stored on the heap, which means
|
||||||
|
the amount of data does not need to be known at compile time and can grow or
|
||||||
|
shrink as the program runs. Each kind of 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:
|
||||||
|
|
||||||
|
* 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. It's a
|
||||||
|
particular implementation of the more general data structure called a *map*.
|
||||||
|
|
||||||
|
To learn about the other kinds of collections provided by the standard library,
|
||||||
|
see [the documentation][collections].
|
||||||
|
|
||||||
|
[collections]: ../std/collections
|
||||||
|
|
||||||
|
We’re going to discuss how to create and update vectors, strings, and hash
|
||||||
|
maps, as well as what makes each special.
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
# Fundamental Collections
|
|
||||||
|
|
||||||
Rust's standard library includes a number of really useful data structures
|
|
||||||
called *collections*. Most other data types represent one specific value, but
|
|
||||||
collections can contain multiple values. Unlike the built-in array and tuple
|
|
||||||
types, the data these collections point to is stored on the heap, which means
|
|
||||||
the amount of data does not need to be known at compile time and can grow or
|
|
||||||
shrink as the program runs. Each kind of 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:
|
|
||||||
|
|
||||||
* 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
|
|
||||||
going to discuss how to create and update each of the collections, as well as
|
|
||||||
what makes each special.
|
|
||||||
+37
-55
@@ -1,6 +1,6 @@
|
|||||||
## Vectors
|
## Vectors
|
||||||
|
|
||||||
The first type we'll look at is `Vec<T>`, also known as a *vector*. Vectors
|
The first type we’ll look at is `Vec<T>`, also known as a *vector*. Vectors
|
||||||
allow us 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. Vectors can only store values of the
|
the values next to each other in memory. Vectors can only store values of the
|
||||||
same type. They are useful in situations where you have a list of items, such
|
same type. They are useful in situations where you have a list of items, such
|
||||||
@@ -14,18 +14,18 @@ To create a new, empty vector, we can call the `Vec::new` function:
|
|||||||
let v: Vec<i32> = Vec::new();
|
let v: Vec<i32> = Vec::new();
|
||||||
```
|
```
|
||||||
|
|
||||||
Note that we added a type annotation here. Since we aren't inserting any values
|
Note that we added a type annotation here. Since we aren’t inserting any values
|
||||||
into this vector, Rust doesn't know what kind of elements we intend to store.
|
into this vector, Rust doesn’t know what kind of elements we intend to store.
|
||||||
This is an important point. Vectors are homogeneous: they may store many values,
|
This is an important point. Vectors are homogeneous: they may store many
|
||||||
but those values must all be the same type. Vectors are implemented using
|
values, but those values must all be the same type. Vectors are implemented
|
||||||
generics, which Chapter 10 will cover how to use in your own types. For now,
|
using generics, which Chapter 10 will cover how to use in your own types. For
|
||||||
all you need to know is that the `Vec` type provided by the standard library
|
now, all you need to know is that the `Vec` type provided by the standard
|
||||||
can hold any type, and when a specific `Vec` holds a specific type, the type
|
library can hold any type, and when a specific `Vec` holds a specific type, the
|
||||||
goes within angle brackets. We've told Rust that the `Vec` in `v` will hold
|
type goes within angle brackets. We’ve told Rust that the `Vec` in `v` will
|
||||||
elements of the `i32` type.
|
hold elements of the `i32` type.
|
||||||
|
|
||||||
In real code, Rust can infer the type of value we want to store once we insert
|
In real code, Rust can infer the type of value we want to store once we insert
|
||||||
values, so you rarely need to do this type annotation. It's more common to
|
values, so you rarely need to do this type annotation. It’s more common to
|
||||||
create a `Vec` that has initial values, and Rust provides the `vec!` macro for
|
create a `Vec` that has initial values, and Rust provides the `vec!` macro for
|
||||||
convenience. The macro will create a new `Vec` that holds the values we give
|
convenience. The macro will create a new `Vec` that holds the values we give
|
||||||
it. This will create a new `Vec<i32>` that holds the values `1`, `2`, and `3`:
|
it. This will create a new `Vec<i32>` that holds the values `1`, `2`, and `3`:
|
||||||
@@ -34,8 +34,8 @@ it. This will create a new `Vec<i32>` that holds the values `1`, `2`, and `3`:
|
|||||||
let v = vec![1, 2, 3];
|
let v = vec![1, 2, 3];
|
||||||
```
|
```
|
||||||
|
|
||||||
Because we've given initial `i32` values, Rust can infer that the type of `v`
|
Because we’ve given initial `i32` values, Rust can infer that the type of `v`
|
||||||
is `Vec<i32>`, and the type annotation isn't necessary. Let's look at how to
|
is `Vec<i32>`, and the type annotation isn’t necessary. Let’s look at how to
|
||||||
modify a vector next.
|
modify a vector next.
|
||||||
|
|
||||||
### Updating a Vector
|
### Updating a Vector
|
||||||
@@ -53,8 +53,8 @@ v.push(8);
|
|||||||
|
|
||||||
As with any variable as we discussed in Chapter 3, if we want to be able to
|
As with any variable as we discussed in Chapter 3, if we want to be able to
|
||||||
change its value, we need to make it mutable with the `mut` keyword. The
|
change its value, we need to make it mutable with the `mut` keyword. The
|
||||||
numbers we place inside are all `i32`s, and Rust infers this from the data, so
|
numbers we place inside are all of type `i32`, and Rust infers this from the
|
||||||
we don't need the `Vec<i32>` annotation.
|
data, so we don’t need the `Vec<i32>` annotation.
|
||||||
|
|
||||||
### Dropping a Vector Drops its Elements
|
### Dropping a Vector Drops its Elements
|
||||||
|
|
||||||
@@ -72,13 +72,13 @@ Like any other `struct`, a vector will be freed when it goes out of scope:
|
|||||||
When the vector gets dropped, all of its contents will also be dropped, meaning
|
When the vector gets dropped, all of its contents will also be dropped, meaning
|
||||||
those integers it holds will be cleaned up. This may seem like a
|
those integers it holds will be cleaned up. This may seem like a
|
||||||
straightforward point, but can get a little more complicated once we start to
|
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!
|
introduce references to the elements of the vector. Let’s tackle that next!
|
||||||
|
|
||||||
### Reading Elements of Vectors
|
### Reading Elements of Vectors
|
||||||
|
|
||||||
Now that you know how to create, update, and destroy vectors, knowing how to
|
Now that you know how to create, update, and destroy vectors, knowing how to
|
||||||
read their contents is a good next step. There are two ways to reference a
|
read their contents is a good next step. There are two ways to reference a
|
||||||
value stored in a vector. In the examples, we've annotated the types of the
|
value stored in a vector. In the examples, we’ve annotated the types of the
|
||||||
values that are returned from these functions for extra clarity.
|
values that are returned from these functions for extra clarity.
|
||||||
|
|
||||||
This example shows both methods of accessing a value in a vector either with
|
This example shows both methods of accessing a value in a vector either with
|
||||||
@@ -94,12 +94,12 @@ let third: Option<&i32> = v.get(2);
|
|||||||
There are a few things to note here. First, that we use the index value of `2`
|
There are a few things to note here. First, that we use the index value of `2`
|
||||||
to get the third element: vectors are indexed by number, starting at zero.
|
to get the third element: vectors are indexed by number, starting at zero.
|
||||||
Second, the two different ways to get the third element are: using `&` and
|
Second, the two different ways to get the third element are: using `&` and
|
||||||
`[]`s, which gives us a reference, or using the `get` method with the index
|
`[]`, which gives us a reference, or using the `get` method with the index
|
||||||
passed as an argument, which gives us an `Option<&T>`.
|
passed as an argument, which gives us an `Option<&T>`.
|
||||||
|
|
||||||
The reason Rust has two ways to reference an element is so that you can choose
|
The reason Rust has two ways to reference an element is so that you can choose
|
||||||
how the program behaves when you try to use an index value that the vector
|
how the program behaves when you try to use an index value that the vector
|
||||||
doesn't have an element for. As an example, what should a program do if it has
|
doesn’t have an element for. As an example, what should a program do if it has
|
||||||
a vector that holds five elements then tries to access an element at index 100
|
a vector that holds five elements then tries to access an element at index 100
|
||||||
like this:
|
like this:
|
||||||
|
|
||||||
@@ -117,12 +117,12 @@ element past the end of the vector to be a fatal error that should crash the
|
|||||||
program.
|
program.
|
||||||
|
|
||||||
When the `get` method is passed an index that is outside the array, it will
|
When the `get` method is passed an index that is outside the array, it will
|
||||||
return `None` without `panic!`ing. You would use this if accessing an element
|
return `None` without panicking. You would use this if accessing an element
|
||||||
beyond the range of the vector will happen occasionally under normal
|
beyond the range of the vector will happen occasionally under normal
|
||||||
circumstances. Your code can then have logic to handle having either
|
circumstances. Your code can then have logic to handle having either
|
||||||
`Some(&element)` or `None`, as we discussed in Chapter 6. For example, the
|
`Some(&element)` or `None`, as we discussed in Chapter 6. For example, the
|
||||||
index could be coming from a person entering a number. If they accidentally
|
index could be coming from a person entering a number. If they accidentally
|
||||||
enter a number that's too large and your program gets a `None` value, you could
|
enter a number that’s too large and your program gets a `None` value, you could
|
||||||
tell the user how many items are in the current `Vec` and give them another
|
tell the user how many items are in the current `Vec` and give them another
|
||||||
chance to enter a valid value. That would be more user-friendly than crashing
|
chance to enter a valid value. That would be more user-friendly than crashing
|
||||||
the program for a typo!
|
the program for a typo!
|
||||||
@@ -132,7 +132,7 @@ the program for a typo!
|
|||||||
Once the program has a valid reference, the borrow checker will enforce the
|
Once the program has a valid reference, the borrow checker will enforce the
|
||||||
ownership and borrowing rules covered in Chapter 4 to ensure this reference and
|
ownership and borrowing rules covered in Chapter 4 to ensure this reference and
|
||||||
any other references to the contents of the vector stay valid. Recall the rule
|
any other references to the contents of the vector stay valid. Recall the rule
|
||||||
that says we can't have mutable and immutable references in the same scope.
|
that says we can’t have mutable and immutable references in the same scope.
|
||||||
That rule applies in this example, where we hold an immutable reference to the
|
That rule applies in this example, where we hold an immutable reference to the
|
||||||
first element in a vector and try to add an element to the end:
|
first element in a vector and try to add an element to the end:
|
||||||
|
|
||||||
@@ -147,7 +147,8 @@ v.push(6);
|
|||||||
Compiling this will give us this error:
|
Compiling this will give us this error:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
|
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as
|
||||||
|
immutable
|
||||||
|
|
|
|
||||||
4 | let first = &v[0];
|
4 | let first = &v[0];
|
||||||
| - immutable borrow occurs here
|
| - immutable borrow occurs here
|
||||||
@@ -160,26 +161,26 @@ error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immuta
|
|||||||
|
|
||||||
This code might look like it should work: why should a reference to the first
|
This code might look like it should work: why should a reference to the first
|
||||||
element care about what changes about the end of the vector? The reason why
|
element care about what changes about the end of the vector? The reason why
|
||||||
this code isn't allowed is due to the way vectors work. Adding a new element
|
this code isn’t allowed is due to the way vectors work. Adding a new element
|
||||||
onto the end of the vector might require allocating new memory and copying the
|
onto the end of the vector might require allocating new memory and copying the
|
||||||
old elements over to the new space, in the circumstance that there isn't enough
|
old elements over to the new space, in the circumstance that there isn’t enough
|
||||||
room to put all the elements next to each other where the vector was. In that
|
room to put all the elements next to each other where the vector was. In that
|
||||||
case, the reference to the first element would be pointing to deallocated
|
case, the reference to the first element would be pointing to deallocated
|
||||||
memory. The borrowing rules prevent programs from ending up in that situation.
|
memory. The borrowing rules prevent programs from ending up in that situation.
|
||||||
|
|
||||||
> Note: For more on this, see [The Nomicon][nomicon].
|
> Note: For more on this, see The Nomicon at
|
||||||
|
*https://doc.rust-lang.org/stable/nomicon/vec.html*.
|
||||||
[nomicon]: https://doc.rust-lang.org/stable/nomicon/vec.html
|
|
||||||
|
|
||||||
### Using an Enum to Store Multiple Types
|
### Using an Enum to Store Multiple Types
|
||||||
|
|
||||||
At the beginning of this chapter, we said that vectors can only store values
|
At the beginning of this chapter, we said that vectors can only store values
|
||||||
that are all the same type. This can be inconvenient; there are definitely use
|
that are all the same type. This can be inconvenient; there are definitely use
|
||||||
cases for needing to store a list of things of different types. Luckily, the
|
cases for needing to store a list of things of different types. Luckily, the
|
||||||
variants of an enum are all defined under the same enum type, so when we need to
|
variants of an enum are all defined under the same enum type, so when we need
|
||||||
store elements of a different type in a vector, we can define and use an enum!
|
to store elements of a different type in a vector, we can define and use an
|
||||||
|
enum!
|
||||||
|
|
||||||
For example, let's say we want to get values from a row in a spreadsheet, where
|
For example, let’s say we want to get values from a row in a spreadsheet, where
|
||||||
some of the columns in the row contain integers, some floating point numbers,
|
some of the columns in the row contain integers, some floating point numbers,
|
||||||
and some strings. We can define an enum whose variants will hold the different
|
and some strings. We can define an enum whose variants will hold the different
|
||||||
value types, and then all of the enum variants will be considered the same
|
value types, and then all of the enum variants will be considered the same
|
||||||
@@ -209,32 +210,13 @@ cause errors with the operations performed on the elements of the vector. Using
|
|||||||
an enum plus a `match` means that Rust will ensure at compile time that we
|
an enum plus a `match` means that Rust will ensure at compile time that we
|
||||||
always handle every possible case, as we discussed in Chapter 6.
|
always handle every possible case, as we discussed in Chapter 6.
|
||||||
|
|
||||||
<!-- Can you briefly explain what the match is doing here, as a recap? How does
|
If you don’t know at the time that you’re writing a program the exhaustive set
|
||||||
it mean we always handle every possible case? I'm not sure it's totally clear.
|
|
||||||
-->
|
|
||||||
<!-- Because this is a focus of chapter 6 rather than this chapter's focus, we
|
|
||||||
don't think we should repeat it here as well, but we added a reference. /Carol
|
|
||||||
-->
|
|
||||||
|
|
||||||
If you don't know at the time that you're writing a program the exhaustive set
|
|
||||||
of types the program will get at runtime to store in a vector, the enum
|
of types the program will get at runtime to store in a vector, the enum
|
||||||
technique won't work. Instead, you can use a trait object, which we'll cover in
|
technique won’t work. Instead, you can use a trait object, which we’ll cover in
|
||||||
Chapter 13.
|
Chapter 17.
|
||||||
|
|
||||||
Now that we've gone over some of the most common ways to use vectors, be sure
|
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 all of the many useful methods
|
to take a look at the API documentation for all of the many useful methods
|
||||||
defined on `Vec` by the standard library. For example, in addition to `push`
|
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
|
there’s a `pop` method that will remove and return the last element. Let’s move
|
||||||
on to the next collection type: `String`!
|
on to the next collection type: `String`!
|
||||||
|
|
||||||
<!-- Do you mean the Rust online documentation here? Are you not including it
|
|
||||||
in the book for space reasons? We might want to justify sending them out of the
|
|
||||||
book if we don't want to cover it here -->
|
|
||||||
|
|
||||||
<!-- Yes, there are many, many methods on Vec: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html
|
|
||||||
Also there are occasionally new methods available with new versions of the
|
|
||||||
language, so there's no way we can be comprehensive here. We want the reader to
|
|
||||||
use the API documentation in these situations since the purpose of the online
|
|
||||||
docs is to be comprehensive and up to date. I personally wouldn't expect a book
|
|
||||||
like this to duplicate the info that's in the API docs, so I don't think a
|
|
||||||
justification is necessary here. /Carol -->
|
|
||||||
|
|||||||
+68
-89
@@ -1,17 +1,17 @@
|
|||||||
## Strings
|
## Strings
|
||||||
|
|
||||||
We've already talked about strings a bunch in Chapter 4, but let's take a more
|
We’ve already talked about strings a bunch in Chapter 4, but let’s take a more
|
||||||
in-depth look at them now. Strings are an area that new Rustaceans commonly get
|
in-depth look at them now. Strings are an area that new Rustaceans commonly get
|
||||||
stuck on. This is due to a combination of three things: Rust's propensity for
|
stuck on. 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
|
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
|
structure than many programmers give them credit for, and UTF-8. These things
|
||||||
combine in a way that can seem difficult when coming from other languages.
|
combine in a way that can seem difficult when coming from other languages.
|
||||||
|
|
||||||
The reason Strings are in the collections chapter is that strings are
|
The reason strings are in the collections chapter is that strings are
|
||||||
implemented as a collection of bytes plus some methods to provide useful
|
implemented as a collection of bytes plus some methods to provide useful
|
||||||
functionality when those bytes are interpreted as text. In this section, we'll
|
functionality when those bytes are interpreted as text. In this section, we’ll
|
||||||
talk about the operations on `String` that every collection type has, like
|
talk about the operations on `String` that every collection type has, like
|
||||||
creating, updating, and reading. We'll also discuss the ways in which `String`
|
creating, updating, and reading. We’ll also discuss the ways in which `String`
|
||||||
is different than the other collections, namely how indexing into a `String` is
|
is different than the other collections, namely how indexing into a `String` is
|
||||||
complicated by the differences in which people and computers interpret `String`
|
complicated by the differences in which people and computers interpret `String`
|
||||||
data.
|
data.
|
||||||
@@ -19,26 +19,26 @@ data.
|
|||||||
### What is a String?
|
### What is a String?
|
||||||
|
|
||||||
Before we can dig into those aspects, we need to talk about what exactly we
|
Before we can dig into those aspects, we need to talk about what exactly we
|
||||||
mean by the term 'string'. Rust actually only has one string type in the core
|
mean by the term *string*. Rust actually only has one string type in the core
|
||||||
language itself: `str`, the string slice, which is usually seen in its borrowed
|
language itself: `str`, the string slice, which is usually seen in its borrowed
|
||||||
form, `&str`. We talked about *string slices* in Chapter 4: these are a
|
form, `&str`. We talked about *string slices* in Chapter 4: these are a
|
||||||
reference to some UTF-8 encoded string data stored elsewhere. String literals,
|
reference to some UTF-8 encoded string data stored elsewhere. String literals,
|
||||||
for example, are stored in the binary output of the program, and are therefore
|
for example, are stored in the binary output of the program, and are therefore
|
||||||
string slices.
|
string slices.
|
||||||
|
|
||||||
The type called `String` is provided in Rust's standard library rather than
|
The type called `String` is provided in Rust’s standard library rather than
|
||||||
coded into the core language, and is a growable, mutable, owned, UTF-8 encoded
|
coded into the core language, and is a growable, mutable, owned, UTF-8 encoded
|
||||||
string type. When Rustaceans talk about 'strings' in Rust, they usually mean
|
string type. When Rustaceans talk about “strings” in Rust, they usually mean
|
||||||
both the `String` and the string slice `&str` types, not just one of those.
|
both the `String` and the string slice `&str` types, not just one of those.
|
||||||
This section is largely about `String`, but both these types are used heavily
|
This section is largely about `String`, but both these types are used heavily
|
||||||
in Rust's standard library. Both `String` and string slices are UTF-8 encoded.
|
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
|
Rust’s standard library also includes a number of other string types, such as
|
||||||
`OsString`, `OsStr`, `CString`, and `CStr`. Library crates may provide even
|
`OsString`, `OsStr`, `CString`, and `CStr`. Library crates may provide even
|
||||||
more options for storing string data. Similar to the `*String`/`*Str` naming,
|
more options for storing string data. Similar to the `*String`/`*Str` naming,
|
||||||
they often provide an owned and borrowed variant, just like `String`/`&str`.
|
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
|
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
|
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
|
types in this chapter; see their API documentation for more about how to use
|
||||||
them and when each is appropriate.
|
them and when each is appropriate.
|
||||||
|
|
||||||
@@ -53,7 +53,7 @@ let s = String::new();
|
|||||||
|
|
||||||
This creates a new empty string called `s` that we can then load data into.
|
This creates a new empty string called `s` that we can then load data into.
|
||||||
|
|
||||||
Often, we'll have some initial data that we'd like to start the string off
|
Often, we’ll have some initial data that we’d like to start the string off
|
||||||
with. For that, we use the `to_string` method, which is available on any type
|
with. For that, we use the `to_string` method, which is available on any type
|
||||||
that implements the `Display` trait, which string literals do:
|
that implements the `Display` trait, which string literals do:
|
||||||
|
|
||||||
@@ -100,8 +100,8 @@ let hello = "Hola";
|
|||||||
|
|
||||||
### Updating a String
|
### Updating a String
|
||||||
|
|
||||||
A `String` can grow in size and its contents can change just like the
|
A `String` can grow in size and its contents can change just like the contents
|
||||||
contents of a `Vec`, by pushing more data into it. In addition, `String` has
|
of a `Vec`, by pushing more data into it. In addition, `String` has
|
||||||
concatenation operations implemented with the `+` operator for convenience.
|
concatenation operations implemented with the `+` operator for convenience.
|
||||||
|
|
||||||
#### Appending to a String with Push
|
#### Appending to a String with Push
|
||||||
@@ -113,9 +113,9 @@ let mut s = String::from("foo");
|
|||||||
s.push_str("bar");
|
s.push_str("bar");
|
||||||
```
|
```
|
||||||
|
|
||||||
`s` will contain "foobar" after these two lines. The `push_str` method takes a
|
`s` will contain “foobar” after these two lines. The `push_str` method takes a
|
||||||
string slice because we don't necessarily want to take ownership of the
|
string slice because we don’t necessarily want to take ownership of the
|
||||||
parameter. For example, it would be unfortunate if we weren't able to use `s2`
|
parameter. For example, it would be unfortunate if we weren’t able to use `s2`
|
||||||
after appending its contents to `s1`:
|
after appending its contents to `s1`:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -132,11 +132,11 @@ let mut s = String::from("lo");
|
|||||||
s.push('l');
|
s.push('l');
|
||||||
```
|
```
|
||||||
|
|
||||||
After this, `s` will contain "lol".
|
After this, `s` will contain “lol”.
|
||||||
|
|
||||||
#### Concatenation with the + Operator or the `format!` Macro
|
#### Concatenation with the + Operator or the `format!` Macro
|
||||||
|
|
||||||
Often, we'll want to combine two existing strings together. One way is to use
|
Often, we’ll want to combine two existing strings together. One way is to use
|
||||||
the `+` operator like this:
|
the `+` operator like this:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -155,16 +155,17 @@ signature looks something like this:
|
|||||||
fn add(self, s: &str) -> String {
|
fn add(self, s: &str) -> String {
|
||||||
```
|
```
|
||||||
|
|
||||||
This isn't the exact signature that's in the standard library; there `add` is
|
This isn’t the exact signature that’s in the standard library; there `add` is
|
||||||
defined using generics. Here, we're looking at the signature of `add` with
|
defined using generics. Here, we’re looking at the signature of `add` with
|
||||||
concrete types substituted for the generic ones, which is what happens when we
|
concrete types substituted for the generic ones, which is what happens when we
|
||||||
call this method with `String` values. This signature gives us the clues we
|
call this method with `String` values. We'll be discussing generics in Chapter
|
||||||
need to understand the tricky bits of the `+` operator.
|
10. This signature gives us the clues we need to understand the tricky bits of
|
||||||
|
the `+` operator.
|
||||||
|
|
||||||
First of all, `s2` has an `&`, meaning that we are adding a *reference* of the
|
First of all, `s2` has an `&`, meaning that we are adding a *reference* of the
|
||||||
second string to the first string. This is because of the `s` parameter in the
|
second string to the first string. This is because of the `s` parameter in the
|
||||||
`add` function: we can only add a `&str` to a `String`, we can't add two
|
`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` values together. Remember back in Chapter 4 when we talked about how
|
||||||
`&String` will coerce to `&str`: we write `&s2` so that the `String` will
|
`&String` will coerce to `&str`: we write `&s2` so that the `String` will
|
||||||
coerce to the proper type, `&str`. Because this method does not take ownership
|
coerce to the proper type, `&str`. Because this method does not take ownership
|
||||||
of the parameter, `s2` will still be valid after this operation.
|
of the parameter, `s2` will still be valid after this operation.
|
||||||
@@ -173,9 +174,9 @@ Second, we can see in the signature that `add` takes ownership of `self`,
|
|||||||
because `self` does *not* have an `&`. This means `s1` in the above example
|
because `self` does *not* have an `&`. This means `s1` in the above example
|
||||||
will be moved into the `add` call and no longer be valid after that. So while
|
will be moved into the `add` call and no longer be valid after that. So while
|
||||||
`let s3 = s1 + &s2;` looks like it will copy both strings and create a new one,
|
`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
|
this statement actually takes ownership of `s1`, appends a copy of the contents
|
||||||
contents, then returns ownership of the result. In other words, it looks like
|
of `s2`, 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
|
it’s making a lot of copies, but isn’t: the implementation is more efficient
|
||||||
than copying.
|
than copying.
|
||||||
|
|
||||||
If we need to concatenate multiple strings, the behavior of `+` gets unwieldy:
|
If we need to concatenate multiple strings, the behavior of `+` gets unwieldy:
|
||||||
@@ -188,8 +189,8 @@ let s3 = String::from("toe");
|
|||||||
let s = s1 + "-" + &s2 + "-" + &s3;
|
let s = s1 + "-" + &s2 + "-" + &s3;
|
||||||
```
|
```
|
||||||
|
|
||||||
`s` will be "tic-tac-toe" at this point. With all of the `+` and `"`
|
`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
|
characters, it gets hard to see what’s going on. For more complicated string
|
||||||
combining, we can use the `format!` macro:
|
combining, we can use the `format!` macro:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -200,22 +201,7 @@ let s3 = String::from("toe");
|
|||||||
let s = format!("{}-{}-{}", s1, s2, s3);
|
let s = format!("{}-{}-{}", s1, s2, s3);
|
||||||
```
|
```
|
||||||
|
|
||||||
<!-- Are we going to discuss the format macro elsewhere at all? If not, some
|
This code will also set `s` to “tic-tac-toe”. The `format!` macro works in the
|
||||||
more info here might be good, this seems like a really useful tool. Is it only
|
|
||||||
used on strings? -->
|
|
||||||
|
|
||||||
<!-- No, we weren't planning on it. We thought it would be sufficient to
|
|
||||||
mention that it works the same way as `println!` since we've covered how
|
|
||||||
`println!` works in Ch 2, "Printing Values with `println!` Placeholders" and Ch
|
|
||||||
5, Ch 5, "Adding Useful Functionality with Derived Traits". `format!` can be
|
|
||||||
used on anything that `println!` can; using `{}` in the format string works
|
|
||||||
with anything that implements the `Display` trait and `{:?}` works with
|
|
||||||
anything that implements the `Debug` trait. Do you have any thoughts on how we
|
|
||||||
could make the similarities with `format!` and `println!` clearer than what we
|
|
||||||
have in the next paragraph without repeating the `println!` content too much?
|
|
||||||
/Carol -->
|
|
||||||
|
|
||||||
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
|
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, and
|
returns a `String` with the contents. This version is much easier to read, and
|
||||||
also does not take ownership of any of its parameters.
|
also does not take ownership of any of its parameters.
|
||||||
@@ -224,7 +210,7 @@ also does not take ownership of any of its parameters.
|
|||||||
|
|
||||||
In many other languages, accessing individual characters in a string by
|
In many other languages, accessing individual characters in a string by
|
||||||
referencing them by index is a valid and common operation. In Rust, however, if
|
referencing them 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.
|
we try to access parts of a `String` using indexing syntax, we’ll get an error.
|
||||||
That is, this code:
|
That is, this code:
|
||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
@@ -243,13 +229,13 @@ satisfied [--explain E0277]
|
|||||||
note: the type `std::string::String` cannot be indexed by `_`
|
note: the type `std::string::String` cannot be indexed by `_`
|
||||||
```
|
```
|
||||||
|
|
||||||
The error and the note tell the story: Rust strings don't support indexing. 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
|
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.
|
bit about how Rust stores strings in memory.
|
||||||
|
|
||||||
#### Internal Representation
|
#### Internal Representation
|
||||||
|
|
||||||
A `String` is a wrapper over a `Vec<u8>`. Let's take a look at some of our
|
A `String` is a wrapper over a `Vec<u8>`. Let’s take a look at some of our
|
||||||
properly-encoded UTF-8 example strings from before. First, this one:
|
properly-encoded UTF-8 example strings from before. First, this one:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -257,17 +243,18 @@ let len = String::from("Hola").len();
|
|||||||
```
|
```
|
||||||
|
|
||||||
In this case, `len` will be four, which means the `Vec` storing the string
|
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
|
“Hola” is four bytes long: each of these letters takes one byte when encoded in
|
||||||
UTF-8. What about this example, though?
|
UTF-8. What about this example, though?
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
let len = String::from("Здравствуйте").len();
|
let len = String::from("Здравствуйте").len();
|
||||||
```
|
```
|
||||||
|
|
||||||
A person asked how long the string is might say 12. However, Rust's answer
|
A person asked how long the string is might say 12. However, Rust’s answer is
|
||||||
is 24. This is the number of bytes that it takes to encode "Здравствуйте" in
|
24. This is the number of bytes that it takes to encode “Здравствуйте” in
|
||||||
UTF-8, since each character takes two bytes of storage. Therefore, an index
|
UTF-8, since each Unicode scalar value takes two bytes of storage. Therefore,
|
||||||
into the string's bytes will not always correlate to a valid character.
|
an index into the string’s bytes will not always correlate to a valid Unicode
|
||||||
|
scalar value.
|
||||||
|
|
||||||
To demonstrate, consider this invalid Rust code:
|
To demonstrate, consider this invalid Rust code:
|
||||||
|
|
||||||
@@ -280,7 +267,7 @@ What should the value of `answer` be? Should it be `З`, the first letter? When
|
|||||||
encoded in UTF-8, the first byte of `З` is `208`, and the second is `151`, so
|
encoded in UTF-8, the first byte of `З` is `208`, and the second is `151`, so
|
||||||
`answer` should in fact be `208`, but `208` is not a valid character on its
|
`answer` should in fact be `208`, but `208` is not a valid character on its
|
||||||
own. Returning `208` is likely not what a person would want if they asked for
|
own. Returning `208` is likely not what a person would want if they asked for
|
||||||
the first letter of this string, but that's the only data that Rust has at byte
|
the first letter of this string, but that’s the only data that Rust has at byte
|
||||||
index 0. Returning the byte value is probably not what people want, even with
|
index 0. Returning the byte value is probably not what people want, even with
|
||||||
only Latin letters: `&"hello"[0]` would return `104`, not `h`. To avoid
|
only Latin letters: `&"hello"[0]` would return `104`, not `h`. To avoid
|
||||||
returning an unexpected value and causing bugs that might not be discovered
|
returning an unexpected value and causing bugs that might not be discovered
|
||||||
@@ -290,18 +277,19 @@ misunderstandings earlier.
|
|||||||
#### 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
|
This leads to another point about UTF-8: there are really three relevant ways
|
||||||
to look at strings, from Rust's perspective: as bytes, scalar values, and
|
to look at strings, from Rust’s perspective: as bytes, scalar values, and
|
||||||
grapheme clusters (the closest thing to what people would call 'letters').
|
grapheme clusters (the closest thing to what people would call *letters*).
|
||||||
|
|
||||||
If we look at the Hindi word "नमस्ते" written in the Devanagari script, it is
|
If we look at the Hindi word “नमस्ते” written in the Devanagari script, it is
|
||||||
ultimately stored as a `Vec` of `u8` values that looks like this:
|
ultimately stored as a `Vec` of `u8` values that looks like this:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135]
|
[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164,
|
||||||
|
224, 165, 135]
|
||||||
```
|
```
|
||||||
|
|
||||||
That's 18 bytes, and is how computers ultimately store this data. If we look at
|
That’s 18 bytes, and is how computers ultimately store this data. If we look at
|
||||||
them as Unicode scalar values, which are what Rust's `char` type is, those
|
them as Unicode scalar values, which are what Rust’s `char` type is, those
|
||||||
bytes look like this:
|
bytes look like this:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@@ -309,8 +297,8 @@ bytes look like this:
|
|||||||
```
|
```
|
||||||
|
|
||||||
There are six `char` values here, but the fourth and sixth are not letters,
|
There are six `char` values here, but the fourth and sixth are not letters,
|
||||||
they're diacritics that don't make sense on their own. Finally, if we look at
|
they’re diacritics that don’t make sense on their own. Finally, if we look at
|
||||||
them as grapheme clusters, we'd get what a person would call the four letters
|
them as grapheme clusters, we’d get what a person would call the four letters
|
||||||
that make up this word:
|
that make up this word:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@@ -323,18 +311,17 @@ what human language the data is in.
|
|||||||
|
|
||||||
A final reason Rust does not allow you to index into a `String` to get a
|
A final reason Rust does not allow you to index into a `String` to get a
|
||||||
character is that indexing operations are expected to always take constant time
|
character is that indexing operations are expected to always take constant time
|
||||||
(O(1)). It isn't possible to guarantee that performance with a `String`,
|
(O(1)). It isn’t possible to guarantee that performance with a `String`,
|
||||||
though, since Rust would have to walk through the contents from the beginning
|
though, since Rust would have to walk through the contents from the beginning
|
||||||
to the index to determine how many valid characters there were.
|
to the index to determine how many valid characters there were.
|
||||||
|
|
||||||
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
|
Because it's not clear what the return type of string indexing should be, and
|
||||||
to be fast. While we can't use `[]` with a single number, we _can_ use `[]`
|
it is often a bad idea to index into a string, Rust dissuades you from doing so
|
||||||
with a range to create a string slice containing particular bytes:
|
by asking you to be more specific if you really need it. The way you can be
|
||||||
|
more specific than indexing using `[]` with a single number is using `[]` with
|
||||||
|
a range to create a string slice containing particular bytes:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
let hello = "Здравствуйте";
|
let hello = "Здравствуйте";
|
||||||
@@ -344,7 +331,7 @@ let s = &hello[0..4];
|
|||||||
|
|
||||||
Here, `s` will be a `&str` that contains the first four bytes of the string.
|
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
|
Earlier, we mentioned that each of these characters was two bytes, so that
|
||||||
means that `s` will be "Зд".
|
means that `s` will be “Зд”.
|
||||||
|
|
||||||
What would happen if we did `&hello[0..1]`? The answer: it will panic at
|
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:
|
runtime, in the same way that accessing an invalid index in a vector does:
|
||||||
@@ -360,10 +347,10 @@ You should use this with caution, since it can cause your program to crash.
|
|||||||
|
|
||||||
Luckily, there are other ways we can access elements in a String.
|
Luckily, there are other ways we can access elements in a String.
|
||||||
|
|
||||||
If we need to perform operations on individual characters, the best way to do
|
If we need to perform operations on individual Unicode scalar values, the best
|
||||||
so is to use the `chars` method. Calling `chars` on "नमस्ते" separates out and
|
way to do so is to use the `chars` method. Calling `chars` on “नमस्ते”
|
||||||
returns six values of type `char`, and you can iterate over the result in order
|
separates out and returns six values of type `char`, and you can iterate over
|
||||||
to access each element:
|
the result in order to access each element:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
for c in "नमस्ते".chars() {
|
for c in "नमस्ते".chars() {
|
||||||
@@ -401,20 +388,12 @@ This code will print the 18 bytes that make up this `String`, starting with:
|
|||||||
// ... etc
|
// ... etc
|
||||||
```
|
```
|
||||||
|
|
||||||
But make sure to remember that valid UTF-8 characters may be made up of more
|
But make sure to remember that valid Unicode scalar values may be made up of
|
||||||
than one byte.
|
more than one byte.
|
||||||
|
|
||||||
Getting grapheme clusters from `String`s is complex, so this functionality is
|
Getting grapheme clusters from strings is complex, so this functionality is not
|
||||||
not provided by the standard library. There are crates available on crates.io
|
provided by the standard library. There are crates available on crates.io if
|
||||||
if this is the functionality you need.
|
this is the functionality you need.
|
||||||
|
|
||||||
<!-- Can you recommend some, or maybe just say why we aren't outlining the
|
|
||||||
method here, ie it's complicated and therefore best to use a crate? -->
|
|
||||||
|
|
||||||
<!-- We're trying not to mention too many crates in the book. Most crates are
|
|
||||||
provided by the community, so we don't want to mention some and not others and
|
|
||||||
seem biased towards certain crates, plus crates can change more quickly (and
|
|
||||||
new crates can be created) than the language and this book will. /Carol -->
|
|
||||||
|
|
||||||
### Strings are Not so Simple
|
### Strings are Not so Simple
|
||||||
|
|
||||||
@@ -427,4 +406,4 @@ of strings than other programming languages do, but this will prevent you from
|
|||||||
having to handle errors involving non-ASCII characters later in your
|
having to handle errors involving non-ASCII characters later in your
|
||||||
development lifecycle.
|
development lifecycle.
|
||||||
|
|
||||||
Let's switch to something a bit less complex: hash map!
|
Let’s switch to something a bit less complex: hash map!
|
||||||
|
|||||||
+57
-61
@@ -1,19 +1,19 @@
|
|||||||
## Hash Maps
|
## Hash Maps
|
||||||
|
|
||||||
The last of our fundamental collections is the *hash map*. The type `HashMap<K,
|
The last of our common collections is the *hash map*. The type `HashMap<K, V>`
|
||||||
V>` stores a mapping of keys of type `K` to values of type `V`. It does this
|
stores a mapping of keys of type `K` to values of type `V`. It does this via a
|
||||||
via a *hashing function*, which determines how it places these keys and values
|
*hashing function*, which determines how it places these keys and values into
|
||||||
into memory. Many different programming languages support this kind of data
|
memory. Many different programming languages support this kind of data
|
||||||
structure, but often with a different name: hash, map, object, hash table, or
|
structure, but often with a different name: hash, map, object, hash table, or
|
||||||
associative array, just to name a few.
|
associative array, just to name a few.
|
||||||
|
|
||||||
Hash maps are useful for when you want to be able to look up data not by an
|
Hash maps are useful for when you want to be able to look up data not by an
|
||||||
index, as you can with vectors, but by using a key that can be of any type. For
|
index, as you can with vectors, but by using a key that can be of any type. For
|
||||||
example, in a game, you could keep track of each team's score in a hash map
|
example, in a game, you could keep track of each team’s score in a hash map
|
||||||
where each key is a team's name and the values are each team's score. Given a
|
where each key is a team’s name and the values are each team’s score. Given a
|
||||||
team name, you can retrieve their score.
|
team name, you can retrieve their score.
|
||||||
|
|
||||||
We'll go over the basic API of hash maps in this chapter, but there are many
|
We’ll go over the basic API of hash maps in this chapter, but there are many
|
||||||
more goodies hiding in the functions defined on `HashMap` by the standard
|
more goodies hiding in the functions defined on `HashMap` by the standard
|
||||||
library. As always, check the standard library documentation for more
|
library. As always, check the standard library documentation for more
|
||||||
information.
|
information.
|
||||||
@@ -21,7 +21,7 @@ information.
|
|||||||
### Creating a New Hash Map
|
### 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`.
|
||||||
Here we're keeping track of the scores of two teams whose names are Blue and
|
Here we’re keeping track of the scores of two teams whose names are Blue and
|
||||||
Yellow. The Blue team will start with 10 points and the Yellow team starts with
|
Yellow. The Blue team will start with 10 points and the Yellow team starts with
|
||||||
50:
|
50:
|
||||||
|
|
||||||
@@ -35,22 +35,22 @@ scores.insert(String::from("Yellow"), 50);
|
|||||||
```
|
```
|
||||||
|
|
||||||
Note that we need to first `use` the `HashMap` from the collections portion of
|
Note that we need to first `use` the `HashMap` from the collections portion of
|
||||||
the standard library. Of our three fundamental collections, this one is the
|
the standard library. Of our three common collections, this one is the least
|
||||||
least often used, so it's not included in the features imported automatically
|
often used, so it’s not included in the features imported automatically in the
|
||||||
in the prelude. Hash maps also have less support from the standard library;
|
prelude. Hash maps also have less support from the standard library; there’s no
|
||||||
there's no built-in macro to construct them, for example.
|
built-in macro to construct them, for example.
|
||||||
|
|
||||||
Just like vectors, hash maps store their data on the heap. This `HashMap` has
|
Just like vectors, hash maps store their data on the heap. This `HashMap` has
|
||||||
keys of type `String` and values of type `i32`. Like vectors, hash maps are
|
keys of type `String` and values of type `i32`. Like vectors, hash maps are
|
||||||
homogeneous: all of the keys must have the same type, and all of the values must
|
homogeneous: all of the keys must have the same type, and all of the values
|
||||||
have the same type.
|
must have the same type.
|
||||||
|
|
||||||
Another way of constructing a hash map is by using the `collect` method on a
|
Another way of constructing a hash map is by using the `collect` method on a
|
||||||
vector of tuples, where each tuple consists of a key and its value. The
|
vector of tuples, where each tuple consists of a key and its value. The
|
||||||
`collect` method gathers up data into a number of collection types, including
|
`collect` method gathers up data into a number of collection types, including
|
||||||
`HashMap`. For example, if we had the team names and initial scores in two
|
`HashMap`. For example, if we had the team names and initial scores in two
|
||||||
separate vectors, we can use the `zip` method to create a vector of tuples
|
separate vectors, we can use the `zip` method to create a vector of tuples
|
||||||
where "Blue" is paired with 10, and so forth. Then we can use the `collect`
|
where “Blue” is paired with 10, and so forth. Then we can use the `collect`
|
||||||
method to turn that vector of tuples into a `HashMap`:
|
method to turn that vector of tuples into a `HashMap`:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -62,8 +62,8 @@ let initial_scores = vec![10, 50];
|
|||||||
let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect();
|
let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect();
|
||||||
```
|
```
|
||||||
|
|
||||||
The type annotation `HashMap<_, _>` is needed here because it's possible to
|
The type annotation `HashMap<_, _>` is needed here because it’s possible to
|
||||||
`collect` into many different data structures, and Rust doesn't know which you
|
`collect` into many different data structures, and Rust doesn’t know which you
|
||||||
want unless you specify. For the type parameters for the key and value types,
|
want unless you specify. For the type parameters for the key and value types,
|
||||||
however, we use underscores and Rust can infer the types that the hash map
|
however, we use underscores and Rust can infer the types that the hash map
|
||||||
contains based on the types of the data in the vector.
|
contains based on the types of the data in the vector.
|
||||||
@@ -109,11 +109,11 @@ let team_name = String::from("Blue");
|
|||||||
let score = scores.get(&team_name);
|
let score = scores.get(&team_name);
|
||||||
```
|
```
|
||||||
|
|
||||||
Here, `score` will have the value that's associated with the Blue team, and the
|
Here, `score` will have the value that’s associated with the Blue team, and the
|
||||||
result will be `Some(10)`. The result is wrapped in `Some` because `get`
|
result will be `Some(10)`. The result is wrapped in `Some` because `get`
|
||||||
returns an `Option<V>`; if there's no value for that key in the hash map, `get`
|
returns an `Option<V>`; if there’s no value for that key in the hash map, `get`
|
||||||
will return `None`. The program will need to handle the `Option` in one of
|
will return `None`. The program will need to handle the `Option` in one of the
|
||||||
the ways that we covered in Chapter 6.
|
ways that we covered in Chapter 6.
|
||||||
|
|
||||||
We can iterate over each key/value pair in a hash map 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:
|
do with vectors, using a `for` loop:
|
||||||
@@ -140,26 +140,21 @@ Blue: 10
|
|||||||
|
|
||||||
### Updating a Hash Map
|
### Updating a Hash Map
|
||||||
|
|
||||||
<!-- So the quantity of keys must be defined up front, that's not growable?
|
|
||||||
That could be worthy saying -->
|
|
||||||
<!-- No, the number of keys is growable, it's just that for EACH individual
|
|
||||||
key, there can only be one value. I've tried to clarify. /Carol -->
|
|
||||||
|
|
||||||
While the number of keys and values is growable, each individual key can only
|
While the number of keys and values is growable, each individual key can only
|
||||||
have one value associated with it at a time. When we want to change the data in
|
have one value associated with it at a time. 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
|
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,
|
value assigned. We could choose to replace the old value with the new value,
|
||||||
completely disregarding the old value. We could choose to keep the old value
|
completely disregarding the old 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*
|
and ignore the new value, and only add the new value if the key *doesn’t*
|
||||||
already have a value. Or we could combine the old value and the new value.
|
already have a value. Or we could combine the old value and the new value.
|
||||||
Let's look at how to do each of these!
|
Let’s look at how to do each of these!
|
||||||
|
|
||||||
#### Overwriting a Value
|
#### Overwriting a Value
|
||||||
|
|
||||||
If we insert a key and a value into a hash map, then insert that same key with a
|
If we insert a key and a value into a hash map, then insert that same key with
|
||||||
different value, the value associated with that key will be replaced. Even
|
a different value, the value associated with that key will be replaced. Even
|
||||||
though this following code calls `insert` twice, the hash map will only contain
|
though this following code calls `insert` twice, the hash map will only contain
|
||||||
one key/value pair because we're inserting the value for the Blue team's key
|
one key/value pair because we’re inserting the value for the Blue team’s key
|
||||||
both times:
|
both times:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -175,17 +170,16 @@ println!("{:?}", scores);
|
|||||||
|
|
||||||
This will print `{"Blue": 25}`. The original value of 10 has been overwritten.
|
This will print `{"Blue": 25}`. The original value of 10 has been overwritten.
|
||||||
|
|
||||||
|
|
||||||
#### Only Insert If the Key Has No Value
|
#### Only Insert If the Key Has No Value
|
||||||
|
|
||||||
It's common to want to check if a particular key has a value and, if it does
|
It’s common to want to check if a particular key has a value and, if it does
|
||||||
not, insert a value for it. Hash maps have a special API for this, called
|
not, insert a value for it. Hash maps have a special API for this, called
|
||||||
`entry`, that takes the key we want to check as an argument. The return value
|
`entry`, that takes the key we want to check as an argument. The return value
|
||||||
of the `entry` function is an enum, `Entry`, that represents a value that might
|
of the `entry` function is an enum, `Entry`, that represents a value that might
|
||||||
or might not exist. Let's say that we want to check if the key for the Yellow
|
or might not exist. Let’s say that we want to check if the key for the Yellow
|
||||||
team has a value associated with it. If it doesn't, we want to insert the value
|
team has a value associated with it. If it doesn’t, we want to insert the value
|
||||||
50, and the same for the Blue team. With the entry API, the code for this
|
50, and the same for the Blue team. With the entry API, the code for this looks
|
||||||
looks like:
|
like:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -199,23 +193,23 @@ scores.entry(String::from("Blue")).or_insert(50);
|
|||||||
println!("{:?}", scores);
|
println!("{:?}", scores);
|
||||||
```
|
```
|
||||||
|
|
||||||
The `or_insert` method on `Entry` returns the value for the `Entry`'s key if it
|
The `or_insert` method on `Entry` returns the value for the corresponding
|
||||||
exists, and if not, inserts its argument as the new value for the `Entry`'s key
|
`Entry` key if it exists, and if not, inserts its argument as the new value for
|
||||||
and returns that. This is much cleaner than writing the logic ourselves, and in
|
this key and returns the modified `Entry`. This is much cleaner than writing
|
||||||
addition, plays more nicely with the borrow checker.
|
the logic ourselves, and in addition, plays more nicely with the borrow checker.
|
||||||
|
|
||||||
This code will print `{"Yellow": 50, "Blue": 10}`. The first call to `entry`
|
This code will print `{"Yellow": 50, "Blue": 10}`. The first call to `entry`
|
||||||
will insert the key for the Yellow team with the value 50, since the Yellow
|
will insert the key for the Yellow team with the value 50, since the Yellow
|
||||||
team doesn't have a value already. The second call to `entry` will not change
|
team doesn’t have a value already. The second call to `entry` will not change
|
||||||
the hash map since the Blue team already has the value 10.
|
the hash map since the Blue team already has the value 10.
|
||||||
|
|
||||||
#### Update a Value Based on the Old Value
|
#### Update a Value Based on the Old Value
|
||||||
|
|
||||||
Another common use case for hash maps 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, based on the old value. For instance, if we wanted to count how many times
|
it, based on the old value. For instance, if we wanted to count how many times
|
||||||
each word appeared in some text, we could use a hash map 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.
|
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`.
|
If this is the first time we’ve seen a word, we’ll first insert the value `0`.
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -247,8 +241,10 @@ hashing algorithm out there, but the tradeoff for better security that comes
|
|||||||
with the drop in performance is worth it. If you profile your code and find
|
with the drop in performance is worth it. If you profile your code and find
|
||||||
that the default hash function is too slow for your purposes, you can switch to
|
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 a type that
|
another function by specifying a different *hasher*. A hasher is a type that
|
||||||
implements the `BuildHasher` trait. We'll be talking about traits and how to
|
implements the `BuildHasher` trait. We’ll be talking about traits and how to
|
||||||
implement them in Chapter 10.
|
implement them in Chapter 10. You don't necessarily have to implement your own
|
||||||
|
hasher from scratch; crates.io has libraries that others have shared that
|
||||||
|
provide hashers implementing many common hashing algorithms.
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
@@ -256,21 +252,21 @@ Vectors, strings, and hash maps will take you far in programs where you need to
|
|||||||
store, access, and modify data. Here are some exercises you should now be
|
store, access, and modify data. Here are some exercises you should now be
|
||||||
equipped to solve:
|
equipped to solve:
|
||||||
|
|
||||||
1. Given a list of integers, use a vector and return the mean (average), median
|
* Given a list of integers, use a vector and return the mean (average), median
|
||||||
(when sorted, the value in the middle position), and mode (the value that
|
(when sorted, the value in the middle position), and mode (the value that
|
||||||
occurs most often; a hash map will be helpful here) of the list.
|
occurs most often; a hash map will be helpful here) of the list.
|
||||||
2. Convert strings to Pig Latin, where the first consonant of each word is
|
* Convert strings to Pig Latin, where the first consonant of each word is moved
|
||||||
moved to the end of the word with an added "ay", so "first" becomes
|
to the end of the word with an added “ay”, so “first” becomes “irst-fay”.
|
||||||
"irst-fay". Words that start with a vowel get "hay" added to the end instead
|
Words that start with a vowel get “hay” added to the end instead (“apple”
|
||||||
("apple" becomes "apple-hay"). Remember about UTF-8 encoding!
|
becomes “apple-hay”). Remember about UTF-8 encoding!
|
||||||
3. Using a hash map 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
|
employee names to a department in the company. For example, “Add Sally to
|
||||||
Engineering" or "Add Amir to Sales". Then let the user retrieve a list of all
|
Engineering” or “Add Amir to Sales”. Then let the user retrieve a list of all
|
||||||
people in a department or all people in the company by department, sorted
|
people in a department or all people in the company by department, sorted
|
||||||
alphabetically.
|
alphabetically.
|
||||||
|
|
||||||
The standard library API documentation describes methods these types have that
|
The standard library API documentation describes methods these types have that
|
||||||
will be helpful for these exercises!
|
will be helpful for these exercises!
|
||||||
|
|
||||||
We're getting into more complex programs where operations can fail, which means
|
We’re getting into more complex programs where operations can fail, which means
|
||||||
it's a perfect time to go over error handling next!
|
it’s a perfect time to go over error handling next!
|
||||||
|
|||||||
Reference in New Issue
Block a user