Merge pull request #342 from rust-lang/ch4-ce

Ch4 copy edit
This commit is contained in:
Carol (Nichols || Goulding)
2016-12-02 14:15:54 -05:00
committed by GitHub
8 changed files with 856 additions and 750 deletions
+413 -372
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
Binary file not shown.
+5 -5
View File
@@ -1,7 +1,7 @@
# Understanding Ownership # Understanding Ownership
Ownership is Rust’s most unique feature, and enables Rust to make memory safety Ownership is Rust’s most unique feature, and it enables Rust to make memory
guarantees without needing a garbage collector. It’s therefore important to safety guarantees without needing a garbage collector. Therefore, it’s
understand how ownership works in Rust. In this chapter we’ll talk about important to understand how ownership works in Rust. In this chapter we’ll talk
ownership as well as several related features: borrowing, slices, and how Rust about ownership as well as several related features: borrowing, slices, and how
lays things out in memory. Rust lays data out in memory.
+253 -221
View File
@@ -1,24 +1,24 @@
## What is Ownership? ## What Is Ownership?
Rust’s central feature is *ownership*. It is a feature that is straightforward Rust’s central feature is *ownership*. Although the feature is straightforward
to explain, but has deep implications for the rest of the language. to explain, it has deep implications for the rest of the language.
All programs have to manage the way they use a computer’s memory while running. All programs have to manage the way they use a computer’s memory while running.
Some languages have garbage collection that’s constantly looking for no longer Some languages have garbage collection that constantly looks for no longer used
used memory as the program runs, while in others, the programmer has to memory as the program runs; in other languages, the programmer must explicitly
explicitly allocate and free the memory. Rust takes a third approach: memory is allocate and free the memory. Rust uses a third approach: memory is managed
managed through a system of ownership with a set of rules that the compiler through a system of ownership with a set of rules that the compiler checks at
checks at compile-time. You do not pay any run-time cost for any of these compile time. No run-time costs are incurred for any of the ownership features.
features.
Since ownership is a new concept for many programmers, it does take some time Because ownership is a new concept for many programmers, it does take some time
to get used to. There is good news, though: the more experienced you become to get used to. The good news is that the more experienced you become with Rust
with Rust and the rules of the ownership system, the more you’ll be able to and the rules of the ownership system, the more you’ll be able to naturally
naturally develop code that is both safe and efficient. Keep at it! develop code that is safe and efficient. Keep at it!
Once you understand ownership, you have a good foundation for understanding the When you understand ownership, you’ll have a solid foundation for understanding
features that make Rust unique. In this chapter, we’ll learn ownership by going the features that make Rust unique. In this chapter, you’ll learn ownership by
through some examples, focusing on a very common data structure: strings. working through some examples that focus on a very common data structure:
strings.
<!-- PROD: START BOX --> <!-- PROD: START BOX -->
@@ -27,9 +27,9 @@ through some examples, focusing on a very common data structure: strings.
> In many programming languages, we don’t have to think about the stack and the > In many programming languages, we don’t have to think about the stack and the
> heap very often. But in a systems programming language like Rust, whether a > heap very often. But in a systems programming language like Rust, whether a
> value is on the stack or the heap has more of an effect on how the language > value is on the stack or the heap has more of an effect on how the language
> behaves and why we have to make certain decisions. We’re going to be > behaves and why we have to make certain decisions. We’ll describe parts of
> describing parts of ownership in relation to the stack and the heap, so here > ownership in relation to the stack and the heap later in this chapter, so here
> is a brief explanation. > is a brief explanation in preparation.
> >
> Both the stack and the heap are parts of memory that is available to your code > Both the stack and the heap are parts of memory that is available to your code
> to use at runtime, but they are structured in different ways. The stack stores > to use at runtime, but they are structured in different ways. The stack stores
@@ -37,58 +37,58 @@ through some examples, focusing on a very common data structure: strings.
> This is referred to as *last in, first out*. Think of a stack of plates: when > This is referred to as *last in, first out*. Think of a stack of plates: when
> you add more plates, you put them on top of the pile, and when you need a > you add more plates, you put them on top of the pile, and when you need a
> plate, you take one off the top. Adding or removing plates from the middle or > plate, you take one off the top. Adding or removing plates from the middle or
> bottom wouldn’t work as well! Adding data is called *pushing onto the stack* > bottom wouldn’t work as well! Adding data is called *pushing onto the stack*,
> and removing data is called *popping off the stack*. > and removing data is called *popping off the stack*.
> >
> The stack is fast because of the way it accesses the data: it never has to > The stack is fast because of the way it accesses the data: it never has to
> look around for a place to put new data or a place to get data from; that > search for a place to put new data or a place to get data from because that
> place is always the top. Another property that makes the stack fast is that > place is always the top. Another property that makes the stack fast is that all
> all data on the stack must take up a known, fixed size. > data on the stack must take up a known, fixed size.
> >
> For data with a size unknown to us at compile time, or a size that might > For data with a size unknown to us at compile time or a size that might change,
> change, we can store data on the heap instead. The heap is less organized: > we can store data on the heap instead. The heap is less organized: when we put
> when we put data on the heap, we ask for some amount of space. The operating > data on the heap, we ask for some amount of space. The operating system finds
> system finds an empty spot somewhere in the heap that is big enough, marks it > an empty spot somewhere in the heap that is big enough, marks it as being in
> as being in use, and returns to us a pointer to that location. This process > use, and returns to us a pointer to that location. This process is called
> is called *allocating on the heap*, and sometimes we just say “allocating” > *allocating on the heap*, and sometimes we abbreviate the phrase as just
> for short. Pushing values onto the stack is not considered allocating. Since > “allocating.” Pushing values onto the stack is not considered allocating.
> the pointer is a known, fixed size, we can store the pointer on the stack, > Because the pointer is a known, fixed size, we can store the pointer on the
> but when we want the actual data, we have to follow the pointer. > stack, but when we want the actual data, we have to follow the pointer.
> >
> Think of being seated at a restaurant. When you enter, you say how many people > Think of being seated at a restaurant. When you enter, you state the number of
> are in your group, and the staff finds an empty table that would fit everyone > people in your group, and the staff finds an empty table that fits everyone and
> and leads you there. If someone in your group comes late, they can ask where > leads you there. If someone in your group comes late, they can ask where you’ve
> you have been seated to find you. > been seated to find you.
> >
> Accessing data in the heap is slower because we have to follow a pointer to > Accessing data in the heap is slower than accessing data on the stack because
> get there. Contemporary processors are faster if they jump around less in > we have to follow a pointer to get there. Contemporary processors are faster if
> memory. Continuing the analogy, consider a server at a restaurant who is > they jump around less in memory. Continuing the analogy, consider a server at a
> taking orders from many tables. It's most efficient to get all of the orders > restaurant taking orders from many tables. It’s most efficient to get all the
> at one table before moving on to the next table. Taking an order from table > orders at one table before moving on to the next table. Taking an order from
> A, then an order from table B, then one from A again, then one from B again > table A, then an order from table B, then one from A again, and then one from B
> would be much slower. By the same token, a processor can do its job better if > again would be a much slower process. By the same token, a processor can do its
> it works on data that's close to other data (as it is on the stack), rather > job better if it works on data that’s close to other data (as it is on the
> than farther away (as it can be on the heap). Allocating a large amount of > stack) rather than farther away (as it can be on the heap). Allocating a large
> space on the heap can also take time. > amount of space on the heap can also take time.
> >
> When our code calls a function, the values passed into the function > When our code calls a function, the values passed into the function (including,
> (including, potentially, pointers to data on the heap) and the function’s > potentially, pointers to data on the heap) and the function’s local variables
> local variables get pushed onto the stack. When the function is over, those > get pushed onto the stack. When the function is over, those values get popped
> values get popped off the stack. > off the stack.
>
> Keeping track of what parts of code are using what data on the heap, minimizing
> the amount of duplicate data on the heap, and cleaning up unused data on the
> heap so we don’t run out of space are all problems that ownership addresses.
> Once you understand ownership, you won’t need to think about the stack and the
> heap very often, but knowing that managing heap data is why ownership exists
> can help explain why it works the way it does.
> >
> Keeping track of what parts of code are using what data on the heap,
> minimizing the amount of duplicate data on the heap, and cleaning up unused
> data on the heap so that we don’t run out of space—these are all problems
> that ownership addresses. Once you understand ownership, you won’t need to
> think about the stack and the heap very often, but knowing that managing heap
> data is why ownership exists can help explain why it works the way it does.
<!-- PROD: END BOX --> <!-- PROD: END BOX -->
### Ownership Rules ### Ownership Rules
First, let’s take a look at the rules. Keep these in mind as we go through the First, let’s take a look at the ownership rules. Keep these rules in mind as we
examples that will illustrate the rules: work through the examples that illustrate the rules:
> 1. Each value in Rust has a variable that’s called its *owner*. > 1. Each value in Rust has a variable that’s called its *owner*.
> 2. There can only be one owner at a time. > 2. There can only be one owner at a time.
@@ -96,12 +96,12 @@ examples that will illustrate the rules:
### Variable Scope ### Variable Scope
We’ve walked through an example of a Rust program already in the tutorial We’ve walked through an example of a Rust program already in Chapter 2. Now
chapter. Now that we’re past basic syntax, we won’t include all of the `fn that we’re past basic syntax, we won’t include all the `fn main() {` code in
main() {` stuff in examples, so if you’re following along, you will have to put examples, so if you’re following along, you’ll have to put the following
the following examples inside of a `main` function yourself. This lets our examples inside a `main` function manually. As a result, our examples will be a
examples be a bit more concise, letting us focus on the actual details rather bit more concise, letting us focus on the actual details rather than
than boilerplate. boilerplate code.
As a first example of ownership, we’ll look at the *scope* of some variables. A As a first example of ownership, we’ll look at the *scope* of some variables. A
scope is the range within a program for which an item is valid. Let’s say we scope is the range within a program for which an item is valid. Let’s say we
@@ -112,8 +112,11 @@ let s = "hello";
``` ```
The variable `s` refers to a string literal, where the value of the string is The variable `s` refers to a string literal, where the value of the string is
hard coded into the text of our program. The variable is valid from the point hardcoded into the text of our program. The variable is valid from the point at
at which it’s declared until the end of the current *scope*. That is: which it’s declared until the end of the current *scope*. Listing 4-1 has
comments annotating where the variable `s` is valid:
<figure>
```rust ```rust
{ // s is not valid here, it’s not yet declared { // s is not valid here, it’s not yet declared
@@ -123,35 +126,42 @@ at which it’s declared until the end of the current *scope*. That is:
} // this scope is now over, and s is no longer valid } // this scope is now over, and s is no longer valid
``` ```
<figcaption>
Listing 4-1: A variable and the scope in which it is valid
</figcaption>
</figure>
In other words, there are two important points in time here: In other words, there are two important points in time here:
- When `s` comes *into scope*, it is valid. 1. When `s` comes *into scope*, it is valid.
- It remains so until it *goes out of scope*. 1. It remains so until it goes *out of scope*.
At this point, things are similar to other programming languages. Now let’s At this point, the relationship between scopes and when variables are valid is
build on top of this understanding by introducing the `String` type. similar to other programming languages. Now we’ll build on top of this
understanding by introducing the `String` type.
### The `String` Type ### The `String` Type
In order to illustrate the rules of ownership, we need a data type that is more To illustrate the rules of ownership, we need a data type that is more complex
complex than the ones we covered in Chapter 3. All of the data types we’ve than the ones we covered in Chapter 3. All the data types we’ve looked at
looked at previously are stored on the stack and popped off the stack when previously are stored on the stack and popped off the stack when their scope is
their scope is over, but we want to look at data that is stored on the heap and over, but we want to look at data that is stored on the heap and explore how
explore how Rust knows when to clean that data up. Rust knows when to clean up that data.
We’re going to use `String` as the example here and concentrate on the parts of We’ll use `String` as the example here and concentrate on the parts of `String`
`String` that relate to ownership. These aspects also apply to other complex that relate to ownership. These aspects also apply to other complex data types
data types provided by the standard library and that you create. We’ll go into provided by the standard library and that you create. We’ll discuss `String` in
more depth about `String` specifically in Chapter 8. more depth in Chapter 8.
We’ve already seen string literals, where a string value is hard-coded into our We’ve already seen string literals, where a string value is hardcoded into our
program. String literals are convenient, but they aren’t always suitable for program. String literals are convenient, but they aren’t always suitable for
every situation you want to use text. For one thing, they’re immutable. For every situation in which you want to use text. One reason is that they’re
another, not every string value can be known when we write our code: what if we immutable. Another is that not every string value can be known when we write
want to take user input and store it? our code: for example, what if we want to take user input and store it? For
these situations, Rust has a second string type, `String`. This type is
For things like this, Rust has a second string type, `String`. This type is allocated on the heap and as such is able to store an amount of text that is
allocated on the heap, and as such, is able to store an amount of text that is
unknown to us at compile time. You can create a `String` from a string literal unknown to us at compile time. You can create a `String` from a string literal
using the `from` function, like so: using the `from` function, like so:
@@ -160,9 +170,10 @@ let s = String::from("hello");
``` ```
The double colon (`::`) is an operator that allows us to namespace this The double colon (`::`) is an operator that allows us to namespace this
particular `from` function under the `String` type itself, rather than using particular `from` function under the `String` type rather than using some sort
some sort of name like `string_from`. We’ll discuss this syntax more in the of name like `string_from`. We’ll discuss this syntax more in the “Method
“Method Syntax” and “Modules” chapters. Syntax” section of Chapter 5 and when we talk about namespacing with modules in
Chapter 7.
This kind of string *can* be mutated: This kind of string *can* be mutated:
@@ -174,82 +185,93 @@ s.push_str(", world!"); // push_str() appends a literal to a String
println!("{}", s); // This will print `hello, world!` println!("{}", s); // This will print `hello, world!`
``` ```
So, what’s the difference here? Why can `String` be mutated, but literals So, what’s the difference here? Why can `String` be mutated but literals
cannot? The difference comes down to how these two types deal with memory. cannot? The difference is how these two types deal with memory.
### Memory and Allocation ### Memory and Allocation
In the case of a string literal, because we know the contents at compile time, In the case of a string literal, we know the contents at compile time so the
the text is hard-coded directly into the final executable. This makes string text is hardcoded directly into the final executable, making string literals
literals quite fast and efficient. But these properties only come from its fast and efficient. But these properties only come from its immutability.
immutability. Unfortunately, we can’t put a blob of memory into the binary for Unfortunately, we can’t put a blob of memory into the binary for each piece of
each piece of text whose size is unknown at compile time and whose size might text whose size is unknown at compile time and whose size might change while
change over the course of running the program. running the program.
With the `String` type, in order to support a mutable, growable piece of text, With the `String` type, in order to support a mutable, growable piece of text,
we need to allocate an amount of memory on the heap, unknown at compile time, we need to allocate an amount of memory on the heap, unknown at compile time,
to hold the contents. This means two things: to hold the contents. This means:
1. The memory must be requested from the operating system at runtime. 1. The memory must be requested from the operating system at runtime.
2. We need a way of giving this memory back to the operating system when we’re 2. We need a way of returning this memory to the operating system when we’re
done with our `String`. done with our `String`.
That first part is done by us: when we call `String::from`, its implementation That first part is done by us: when we call `String::from`, its implementation
requests the memory it needs. This is pretty much universal in programming requests the memory it needs. This is pretty much universal in programming
languages. languages.
The second case, however, is different. In languages with a *garbage collector* However, the second part is different. In languages with a *garbage collector
(GC), the GC will keep track and clean up memory that isn’t being used anymore, (GC)*, the GC keeps track and cleans up memory that isn’t being used anymore,
and we, as the programmer, don’t need to think about it. Without GC, it’s the and we, as the programmer, don’t need to think about it. Without a GC, it’s the
programmer’s responsibility to identify when memory is no longer being used and programmer’s responsibility to identify when memory is no longer being used and
call code to explicitly return it, just as we did to request it. Doing this call code to explicitly return it, just as we did to request it. Doing this
correctly has historically been a difficult problem in programming. If we correctly has historically been a difficult programming problem. If we forget,
forget, we will waste memory. If we do it too early, we will have an invalid we’ll waste memory. If we do it too early, we’ll have an invalid variable. If
variable. If we do it twice, that’s a bug too. We need to pair exactly one we do it twice, that’s a bug too. We need to pair exactly one `allocate` with
`allocate` with exactly one `free`. exactly one `free`.
Rust takes a different path: the memory is automatically returned once the Rust takes a different path: the memory is automatically returned once the
variable that owns it goes out of scope. Here’s a version of our scope example variable that owns it goes out of scope. Here’s a version of our scope example
from earlier using `String`: from Listing 4-1 using a `String` instead of a string literal:
```rust ```rust
{ {
let s = String::from("hello"); // s is valid from this point forward let s = String::from("hello"); // s is valid from this point forward
// do stuff with s // do stuff with s
} // this scope is now over, and s is no longer valid } // this scope is now over, and s is no
// longer valid
``` ```
There is a natural point at which we can return the memory our `String` needs There is a natural point at which we can return the memory our `String` needs
back to the operating system: when `s` goes out of scope. When a variable goes to the operating system: when `s` goes out of scope. When a variable goes out
out of scope, Rust calls a special function for us. This function is called of scope, Rust calls a special function for us. This function is called `drop`,
`drop`, and it is where the author of `String` can put the code to return the and it’s where the author of `String` can put the code to return the memory.
memory. Rust calls `drop` automatically at the closing `}`. Rust calls `drop` automatically at the closing `}`.
> Note: This pattern is sometimes called *Resource Acquisition Is > Note: In C++, this pattern of deallocating resources at the end of an item's
> Initialization* in C++, or RAII for short. The `drop` function in Rust will be > lifetime is sometimes called *Resource Acquisition Is Initialization (RAII)*.
> familiar to you if you have used RAII patterns. > The `drop` function in Rust will be familiar to you if you’ve used RAII
> patterns.
This pattern has a profound impact on the way that Rust code is written. It may This pattern has a profound impact on the way Rust code is written. It may seem
seem simple right now, but things can get tricky in more advanced situations simple right now, but the behavior of code can be unexpected in more
when we want to have multiple variables use the data that we have allocated on complicated situations when we want to have multiple variables use the data
the heap. Let’s go over some of those situations now. we’ve allocated on the heap. Let’s explore some of those situations now.
#### Ways Variables and Data Interact: Move #### Ways Variables and Data Interact: Move
There are different ways that multiple variables can interact with the same data Multiple variables can interact with the same data in different ways in Rust.
in Rust. Let’s take an example using an integer: Let’s look at an example using an integer in Listing 4-2:
<figure>
```rust ```rust
let x = 5; let x = 5;
let y = x; let y = x;
``` ```
<figcaption>
Listing 4-2: Assigning the integer value of variable `x` to `y`
</figcaption>
</figure>
We can probably guess what this is doing based on our experience with other We can probably guess what this is doing based on our experience with other
languages: “Bind the value `5` to `x`, then make a copy of the value in `x` and languages: “Bind the value `5` to `x`; then make a copy of the value in `x` and
bind it to `y`.” We now have two variables, `x` and `y`, and both equal `5`. bind it to `y`.” We now have two variables, `x` and `y`, and both equal `5`.
This is indeed what is happening since integers are simple values with a known, This is indeed what is happening because integers are simple values with a
fixed size, and these two `5` values are pushed onto the stack. known, fixed size, and these two `5` values are pushed onto the stack.
Now let’s look at the `String` version: Now let’s look at the `String` version:
@@ -259,21 +281,21 @@ let s2 = s1;
``` ```
This looks very similar to the previous code, so we might assume that the way This looks very similar to the previous code, so we might assume that the way
it works would be the same: that the second line would make a copy of the value it works would be the same: that is, the second line would make a copy of the
in `s1` and bind it to `s2`. This isn’t quite what happens. value in `s1` and bind it to `s2`. But this isn’t quite what happens.
To explain this more thoroughly, let’s take a look at what `String` looks like To explain this more thoroughly, let’s look at what `String` looks like under
under the covers in Figure 4-1. A `String` is made up of three parts, shown on the covers in Figure 4-3. A `String` is made up of three parts, shown on the
the left: a pointer to the memory that holds the contents of the string, a left: a pointer to the memory that holds the contents of the string, a length,
length, and a capacity. This group of data is stored on the stack. On the right and a capacity. This group of data is stored on the stack. On the right is the
is the memory that holds the contents, and this is on the heap. memory on the heap that holds the contents.
<figure> <figure>
<img alt="String in memory" src="img/trpl04-01.svg" class="center" style="width: 50%;" /> <img alt="String in memory" src="img/trpl04-01.svg" class="center" style="width: 50%;" />
<figcaption> <figcaption>
Figure 4-1: Representation in memory of a `String` holding the value `"hello"` Figure 4-3: Representation in memory of a `String` holding the value `"hello"`
bound to `s1` bound to `s1`
</figcaption> </figcaption>
@@ -281,54 +303,55 @@ bound to `s1`
The length is how much memory, in bytes, the contents of the `String` is The length is how much memory, in bytes, the contents of the `String` is
currently using. The capacity is the total amount of memory, in bytes, that the currently using. The capacity is the total amount of memory, in bytes, that the
`String` has gotten from the operating system. The difference between length `String` has received from the operating system. The difference between length
and capacity matters but not in this context, so for now, it’s fine to ignore and capacity matters, but not in this context, so for now, it’s fine to ignore
the capacity. the capacity.
When we assign `s1` to `s2`, the `String` data itself is copied, meaning we When we assign `s1` to `s2`, the `String` data is copied, meaning we copy the
copy the pointer, the length, and the capacity that are on the stack. We do not pointer, the length, and the capacity that are on the stack. We do not copy the
copy the data on the heap that the `String`’s pointer refers to. In other data on the heap that the pointer refers to. In other words, the data
words, it looks like figure 4-2. representation in memory looks like Figure 4-4.
<figure> <figure>
<img alt="s1 and s2 pointing to the same value" src="img/trpl04-02.svg" class="center" style="width: 50%;" /> <img alt="s1 and s2 pointing to the same value" src="img/trpl04-02.svg" class="center" style="width: 50%;" />
<figcaption> <figcaption>
Figure 4-2: Representation in memory of the variable `s2` that has a copy of Figure 4-4: Representation in memory of the variable `s2` that has a copy of
`s1`’s pointer, length and capacity the pointer, length, and capacity of `s1`
</figcaption> </figcaption>
</figure> </figure>
And *not* Figure 4-3, which is what memory would look like if Rust instead The representation does *not* look like Figure 4-5, which is what memory would
copied the heap data as well. If Rust did this, the operation `s2 = s1` could look like if Rust instead copied the heap data as well. If Rust did this, the
potentially be very expensive if the data on the heap was large. operation `s2 = s1` could potentially be very expensive in terms of runtime
performance if the data on the heap was large.
<figure> <figure>
<img alt="s1 and s2 to two places" src="img/trpl04-03.svg" class="center" style="width: 50%;" /> <img alt="s1 and s2 to two places" src="img/trpl04-03.svg" class="center" style="width: 50%;" />
<figcaption> <figcaption>
Figure 4-3: Another possibility for what `s2 = s1` might do, if Rust chose to Figure 4-5: Another possibility of what `s2 = s1` might do if Rust copied the
copy heap data as well. heap data as well
</figcaption> </figcaption>
</figure> </figure>
Earlier, we said that when a variable goes out of scope, Rust will Earlier, we said that when a variable goes out of scope, Rust automatically
automatically call the `drop` function and clean up the heap memory for that calls the `drop` function and cleans up the heap memory for that variable. But
variable. But in figure 4-2, we see both data pointers pointing to the same Figure 4-4 shows both data pointers pointing to the same location. This is a
location. This is a problem: when `s2` and `s1` go out of scope, they will both problem: when `s2` and `s1` go out of scope, they will both try to free the
try to free the same memory. This is known as a *double free* error and is one same memory. This is known as a *double free* error and is one of the memory
of the memory safety bugs we mentioned before. Freeing memory twice can lead to safety bugs we mentioned previously. Freeing memory twice can lead to memory
memory corruption, which can potentially lead to security vulnerabilities. corruption, which can potentially lead to security vulnerabilities.
In order to ensure memory safety, there’s one more detail to what happens in To ensure memory safety, there’s one more detail to what happens in this
this situation in Rust. Instead of trying to copy the allocated memory, Rust situation in Rust. Instead of trying to copy the allocated memory, Rust
says that `s1` is no longer valid and, therefore, doesn’t need to free anything considers `s1` to no longer be valid and therefore, Rust doesn’t need to free
when it goes out of scope. Check out what happens when you try to use `s1` anything when `s1` goes out of scope. Check out what happens when you try to
after `s2` is created: use `s1` after `s2` is created:
```rust,ignore ```rust,ignore
let s1 = String::from("hello"); let s1 = String::from("hello");
@@ -337,31 +360,33 @@ let s2 = s1;
println!("{}", s1); println!("{}", s1);
``` ```
You’ll get an error like this: You’ll get an error like this because Rust prevents you from using the
invalidated reference:
```text ```text
5:22 error: use of moved value: `s1` [E0382] 5:22 error: use of moved value: `s1` [E0382]
println!("{}", s1); println!("{}", s1);
^~ ^~
5:24 note: in this expansion of println! (defined in <std macros>) 5:24 note: in this expansion of println! (defined in <std macros>)
3:11 note: `s1` moved here because it has type `collections::string::String`, which is moved by default 3:11 note: `s1` moved here because it has type `collections::string::String`,
which is moved by default
let s2 = s1; let s2 = s1;
^~ ^~
``` ```
If you have heard the terms “shallow copy” and “deep copy” while working with If you’ve heard the terms “shallow copy” and “deep copy” while working with
other languages, the concept of copying the pointer, length, and capacity other languages, the concept of copying the pointer, length, and capacity
without copying the data probably sounds like a shallow copy. But because Rust without copying the data probably sounds like a shallow copy. But because Rust
also invalidates the first variable, instead of calling this a shallow copy, also invalidates the first variable, instead of calling this a shallow copy,
it’s known as a *move*. Here we would read this by saying that `s1` was *moved* it’s known as a *move*. Here we would read this by saying that `s1` was *moved*
into `s2`. So what actually happens looks like Figure 4-4. into `s2`. So what actually happens is shown in Figure 4-6.
<figure> <figure>
<img alt="s1 moved to s2" src="img/trpl04-04.svg" class="center" style="width: 50%;" /> <img alt="s1 moved to s2" src="img/trpl04-04.svg" class="center" style="width: 50%;" />
<figcaption> <figcaption>
Figure 4-4: Representation in memory after `s1` has been invalidated Figure 4-6: Representation in memory after `s1` has been invalidated
</figcaption> </figcaption>
</figure> </figure>
@@ -369,19 +394,16 @@ Figure 4-4: Representation in memory after `s1` has been invalidated
That solves our problem! With only `s2` valid, when it goes out of scope, it That solves our problem! With only `s2` valid, when it goes out of scope, it
alone will free the memory, and we’re done. alone will free the memory, and we’re done.
Furthermore, there’s a design choice that’s implied by this: Rust will never In addition, there’s a design choice that’s implied by this: Rust will never
automatically create “deep” copies of your data. Therefore, any *automatic* automatically create “deep” copies of your data. Therefore, any *automatic*
copying can be assumed to be inexpensive. copying can be assumed to be inexpensive in terms of runtime performance.
#### Ways Variables and Data Interact: Clone #### Ways Variables and Data Interact: Clone
If we *do* want to deeply copy the `String`’s data and not just the `String` If we *do* want to deeply copy the heap data of the `String`, not just the
itself, there’s a common method for that: `clone`. We will discuss methods in stack data, we can use a common method called `clone`. We’ll discuss method
the section on [`structs` in Chapter 5][structs]<!-- ignore -->, but they’re a syntax in Chapter 5, but because methods are a common feature in many
common enough feature in many programming languages that you have probably seen programming languages, you’ve probably seen them before.
them before.
[structs]: ch05-01-structs.html
Here’s an example of the `clone` method in action: Here’s an example of the `clone` method in action:
@@ -392,17 +414,17 @@ let s2 = s1.clone();
println!("s1 = {}, s2 = {}", s1, s2); println!("s1 = {}, s2 = {}", s1, s2);
``` ```
This will work just fine, and this is how you can explicitly get the behavior This works just fine and is how you can explicitly produce the behavior shown
we showed in Figure 4-3, where the heap data *does* get copied. in Figure 4-4, where the heap data *does* get copied.
When you see a call to `clone`, you know that some arbitrary code is being When you see a call to `clone`, you know that some arbitrary code is being
executed, and that code may be expensive. It’s a visual indicator that executed and that code may be expensive. It’s a visual indicator that something
something different is going on here. different is going on.
#### Stack-only Data: Copy #### Stack-Only Data: Copy
There’s another wrinkle we haven’t talked about yet. This code, that we showed There’s another wrinkle we haven’t talked about yet. This code using integers,
earlier, works and is valid: part of which was shown earlier in Listing 4-2, works and is valid:
```rust ```rust
let x = 5; let x = 5;
@@ -411,49 +433,50 @@ let y = x;
println!("x = {}, y = {}", x, y); println!("x = {}, y = {}", x, y);
``` ```
This seems to contradict what we just learned: we don’t have a call to `clone`, But this code seems to contradict what we just learned: we don’t have a call to
but `x` is still valid, and wasn’t moved into `y`. `clone`, but `x` is still valid and wasn’t moved into `y`.
This is because types like integers that have a known size at compile time are The reason is that types like integers that have a known size at compile time
stored entirely on the stack, so copies of the actual values are quick to make. are stored entirely on the stack, so copies of the actual values are quick to
That means there’s no reason we would want to prevent `x` from being valid make. That means there’s no reason we would want to prevent `x` from being
after we create the variable `y`. In other words, there’s no difference between valid after we create the variable `y`. In other words, there’s no difference
deep and shallow copying here, so calling `clone` wouldn’t do anything between deep and shallow copying here, so calling `clone` wouldn’t do anything
differently from the usual shallow copying and we can leave it out. differently from the usual shallow copying and we can leave it out.
Rust has a special annotation called the `Copy` trait that we can place on Rust has a special annotation called the `Copy` trait that we can place on
types like these (we’ll talk more about traits in Chapter 10). If a type has types like integers that are stored on the stack (we’ll talk more about traits
the `Copy` trait, an older variable is still usable after assignment. Rust will in Chapter 10). If a type has the `Copy` trait, an older variable is still
not let us annotate a type with the `Copy` trait if the type, or any of its usable after assignment. Rust won’t let us annotate a type with the `Copy`
parts, has implemented the `Drop` trait. If the type needs something special trait if the type, or any of its parts, has implemented the `D``rop` trait. If
to happen when the value goes out of scope and we add the `Copy` annotation to the type needs something special to happen when the value goes out of scope and
that type, we will get a compile-time error. we add the `Copy` annotation to that type, we’ll get a compile time error.
So what types are `Copy`? You can check the documentation for the given type to So what types are `Copy`? You can check the documentation for the given type to
be sure, but as a rule of thumb, any group of simple scalar values can be Copy, be sure, but as a general rule, any group of simple scalar values can be
and nothing that requires allocation or is some form of resource is `Copy`. `Copy`, and nothing that requires allocation or is some form of resource is
Here’s some of the types that are `Copy`: `Copy`. Here are some of the types that are `Copy`:
* All of the integer types, like `u32`. * All the integer types, like `u32`.
* The boolean type, `bool`, with values `true` and `false`. * The boolean type, `bool`, with values `true` and `false`.
* All of the floating point types, like `f64`. * All the floating point types, like `f64`.
* Tuples, but only if they contain types which are also `Copy`. `(i32, i32)` is * Tuples, but only if they contain types that are also `Copy`. `(i32, i32)` is
`Copy`, but `(i32, String)` is not. `Copy`, but `(i32, String)` is not.
### Ownership and Functions ### Ownership and Functions
The semantics for passing a value to a function are similar to assigning a The semantics for passing a value to a function are similar to assigning a
value to a variable. Passing a variable to a function will move or copy, just value to a variable. Passing a variable to a function will move or copy, just
like assignment. Here’s an example, with some annotations showing where like assignment. Listing 4-7 has an example with some annotations showing where
variables go into and out of scope: variables go into and out of scope:
<figure>
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
```rust ```rust
fn main() { fn main() {
let s = String::from("hello"); // s comes into scope. let s = String::from("hello"); // s comes into scope.
takes_ownership(s); // s’s value moves into the function... takes_ownership(s); // s's value moves into the function...
// ... and so is no longer valid here. // ... and so is no longer valid here.
let x = 5; // x comes into scope. let x = 5; // x comes into scope.
@@ -461,7 +484,7 @@ fn main() {
// but i32 is Copy, so it’s okay to still // but i32 is Copy, so it’s okay to still
// use x afterward. // use x afterward.
} // Here, x goes out of scope, then s. But since s’s value was moved, nothing } // Here, x goes out of scope, then s. But since s's value was moved, nothing
// special happens. // special happens.
fn takes_ownership(some_string: String) { // some_string comes into scope. fn takes_ownership(some_string: String) { // some_string comes into scope.
@@ -474,15 +497,22 @@ fn makes_copy(some_integer: i32) { // some_integer comes into scope.
} // Here, some_integer goes out of scope. Nothing special happens. } // Here, some_integer goes out of scope. Nothing special happens.
``` ```
<figcaption>
Listing 4-7: Functions with ownership and scope annotated
</figcaption>
</figure>
If we tried to use `s` after the call to `takes_ownership`, Rust would throw a If we tried to use `s` after the call to `takes_ownership`, Rust would throw a
compile-time error. These static checks protect us from mistakes. Try adding compile time error. These static checks protect us from mistakes. Try adding
code to `main` that uses `s` and `x` to see where you can use them and where code to `main` that uses `s` and `x` to see where you can use them and where
the ownership rules prevent you from doing so. the ownership rules prevent you from doing so.
### Return Values and Scope ### Return Values and Scope
Returning values can also transfer ownership. Here’s an example with similar Returning values can also transfer ownership. Here’s an example with similar
annotations: annotations to those in Listing 4-7:
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
@@ -491,13 +521,13 @@ fn main() {
let s1 = gives_ownership(); // gives_ownership moves its return let s1 = gives_ownership(); // gives_ownership moves its return
// value into s1. // value into s1.
let s2 = String::from("hello"); // s2 comes into scope let s2 = String::from("hello"); // s2 comes into scope.
let s3 = takes_and_gives_back(s2); // s2 is moved into let s3 = takes_and_gives_back(s2); // s2 is moved into
// takes_and_gives_back, which also // takes_and_gives_back, which also
// moves its return value into s3. // moves its return value into s3.
} // Here, s3 goes out of scope, and is dropped. s2 goes out of scope, but was } // Here, s3 goes out of scope and is dropped. s2 goes out of scope but was
// moved, so nothing happens. s1 goes out of scope, and is dropped. // moved, so nothing happens. s1 goes out of scope and is dropped.
fn gives_ownership() -> String { // gives_ownership will move its fn gives_ownership() -> String { // gives_ownership will move its
// return value into the function // return value into the function
@@ -505,30 +535,31 @@ fn gives_ownership() -> String { // gives_ownership will move its
let some_string = String::from("hello"); // some_string comes into scope. let some_string = String::from("hello"); // some_string comes into scope.
some_string // some_string is returned, and some_string // some_string is returned and
// moves out to the calling // moves out to the calling
// function. // function.
} }
// takes_and_gives_back will both take a String and return one // takes_and_gives_back will take a String and return one.
fn takes_and_gives_back(a_string: String) -> String { // a_string comes into scope fn takes_and_gives_back(a_string: String) -> String { // a_string comes into
// scope.
a_string // a_string is returned, and moves out to the calling function a_string // a_string is returned and moves out to the calling function.
} }
``` ```
It’s the same pattern, every time: assigning a value to another variable moves The ownership of variables follows the same pattern every time: assigning a
it, and when heap data values’ variables go out of scope, if the data hasn’t value to another variable moves it, and when heap data values’ variables go out
been moved to be owned by another variable, the value will be cleaned up by of scope, if the data hasn’t been moved to be owned by another variable, the
`drop`. value will be cleaned up by `drop`.
Taking ownership then returning ownership with every function is a bit tedious. Taking ownership and then returning ownership with every function is a bit
What if we want to let a function use a value but not take ownership? It’s tedious. What if we want to let a function use a value but not take ownership?
quite annoying that anything we pass in also needs to be passed back if we want It’s quite annoying that anything we pass in also needs to be passed back if we
to use it again, in addition to any data resulting from the body of the want to use it again, in addition to any data resulting from the body of the
function that we might want to return as well. function that we might want to return as well.
It is possible to return multiple values using a tuple, like this: It’s possible to return multiple values using a tuple, like this:
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
@@ -549,4 +580,5 @@ fn calculate_length(s: String) -> (String, usize) {
``` ```
But this is too much ceremony and a lot of work for a concept that should be But this is too much ceremony and a lot of work for a concept that should be
common. Luckily for us, Rust has a feature for this concept: references. common. Luckily for us, Rust has a feature for this concept, and it’s called
*references*.
+73 -62
View File
@@ -1,8 +1,8 @@
## References and Borrowing ## References and Borrowing
The issue with the tuple code at the end of the last section is that we have to The issue with the tuple code at the end of the preceding section is that we
return the `String` back to the calling function so that we can still use the have to return the `String` to the calling function so we can still use the
`String` after the call to `calculate_length`, since the `String` was moved `String` after the call to `calculate_length`, because the `String` was moved
into `calculate_length`. into `calculate_length`.
Here is how you would define and use a `calculate_length` function that takes a Here is how you would define and use a `calculate_length` function that takes a
@@ -25,20 +25,20 @@ fn calculate_length(s: &String) -> usize {
} }
``` ```
First, you’ll notice all of the tuple stuff in the variable declaration and the First, notice that all the tuple code in the variable declaration and the
function return value is gone. Next, note that we pass `&s1` into function return value is gone. Second, note that we pass `&s1` into
`calculate_length`, and in its definition, we take `&String` rather than `calculate_length`, and in its definition, we take `&String` rather than
`String`. `String`.
These `&`s are *references*, and they allow you to refer to some value without These ampersands are *references*, and they allow you to refer to some value
taking ownership of it. Figure 4-5 shows a diagram of this. without taking ownership of it. Figure 4-8 shows a diagram.
<figure> <figure>
<img alt="&String s pointing at String s1" src="img/trpl04-05.svg" class="center" /> <img alt="&String s pointing at String s1" src="img/trpl04-05.svg" class="center" />
<figcaption> <figcaption>
Figure 4-5: `&String s` pointing at `String s1` Figure 4-8: `&String s` pointing at `String s1`
</figcaption> </figcaption>
</figure> </figure>
@@ -54,7 +54,7 @@ let s1 = String::from("hello");
let len = calculate_length(&s1); let len = calculate_length(&s1);
``` ```
The `&s1` syntax lets us create a reference which *refers* to the value of `s1` The `&s1` syntax lets us create a reference that *refers* to the value of `s1`
but does not own it. Because it does not own it, the value it points to will but does not own it. Because it does not own it, the value it points to will
not be dropped when the reference goes out of scope. not be dropped when the reference goes out of scope.
@@ -64,22 +64,24 @@ reference as an argument. Let’s add some explanatory annotations:
```rust ```rust
fn calculate_length(s: &String) -> usize { // s is a reference to a String fn calculate_length(s: &String) -> usize { // s is a reference to a String
s.len() s.len()
} // Here, s goes out of scope. But since it does not have ownership of what } // Here, s goes out of scope. But because it does not have ownership of what
// it refers to, nothing happens. // it refers to, nothing happens.
``` ```
It’s the same process as before, but we don’t drop what the reference points to The scope in which the variable `s` is valid is the same as any function
when it goes out of scope because we don’t have ownership. This lets us write argument's scope, but we don’t drop what the reference points to when it goes
functions which take references as arguments instead of the values themselves, out of scope because we don’t have ownership. Functions that take references as
so that we won’t need to return them to give back ownership. arguments instead of the actual values mean we won’t need to return the values
in order to give back ownership, since we never had ownership.
We call this process *borrowing*. Just like with real life, if a person owns We call taking references as function arguments *borrowing*. As in real life,
something, you can borrow it from them, and when you’re done, you have to give if a person owns something, you can borrow it from them. When you’re done, you
it back. have to give it back.
So what happens if we try to modify something we’re borrowing? Try this code So what happens if we try to modify something we’re borrowing? Try the code in
out. Spoiler alert: it doesn’t work! Listing 4-9. Spoiler alert: it doesn’t work!
<figure>
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
```rust,ignore ```rust,ignore
@@ -94,6 +96,13 @@ fn change(some_string: &String) {
} }
``` ```
<figcaption>
Listing 4-9: Attempting to modify a borrowed value
</figcaption>
</figure>
Here’s the error: Here’s the error:
```text ```text
@@ -104,12 +113,12 @@ error: cannot borrow immutable borrowed content `*some_string` as mutable
| ^^^^^^^^^^^ | ^^^^^^^^^^^
``` ```
Just as variables are immutable by default, so are references. We’re not allowed Just as variables are immutable by default, so are references. We’re not
to modify something we have a reference to. allowed to modify something we have a reference to.
### Mutable References ### Mutable References
We can fix this error with just a small tweak: We can fix the error in the code from Listing 4-9 with just a small tweak:
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
@@ -129,9 +138,9 @@ First, we had to change `s` to be `mut`. Then we had to create a mutable
reference with `&mut s` and accept a mutable reference with `some_string: &mut reference with `&mut s` and accept a mutable reference with `some_string: &mut
String`. String`.
Mutable references have one big restriction, though: you can only have one But mutable references have one big restriction: you can only have one mutable
mutable reference to a particular piece of data in a particular scope. This reference to a particular piece of data in a particular scope. This code will
code will fail: fail:
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
@@ -156,24 +165,24 @@ error[E0499]: cannot borrow `s` as mutable more than once at a time
| - first borrow ends here | - first borrow ends here
``` ```
This restriction allows for mutation but in a very controlled fashion. It is This restriction allows for mutation but in a very controlled fashion. It’s
something that new Rustaceans struggle with, because most languages let you something that new Rustaceans struggle with, because most languages let you
mutate whenever you’d like. The benefit of having this restriction is that Rust mutate whenever you’d like. The benefit of having this restriction is that Rust
can prevent data races at compile time. can prevent data races at compile time.
A *data race* is a particular type of race condition where these three things A *data race* is a particular type of race condition in which these three
occur: behaviors occur:
1. Two or more pointers access the same data at the same time 1. Two or more pointers access the same data at the same time.
1. At least one of the pointers is being used to write to the data 1. At least one of the pointers is being used to write to the data.
1. There’s no mechanism being used to synchronize access to the data 1. There’s no mechanism being used to synchronize access to the data.
Data races cause undefined behavior and can be difficult to diagnose and fix Data races cause undefined behavior and can be difficult to diagnose and fix
when trying to track them down at runtime; Rust prevents this problem from when you’re trying to track them down at runtime; Rust prevents this problem
happening since it won’t even compile code with data races! from happening because it won’t even compile code with data races!
As always, we can use `{}`s to create a new scope, allowing for multiple As always, we can use curly brackets to create a new scope, allowing for
mutable references, just not *simultaneous* ones: multiple mutable references, just not *simultaneous* ones:
```rust ```rust
let mut s = String::from("hello"); let mut s = String::from("hello");
@@ -186,8 +195,8 @@ let mut s = String::from("hello");
let r2 = &mut s; let r2 = &mut s;
``` ```
There is a similar rule for combining mutable and immutable references. This A similar rule exists for combining mutable and immutable references. This code
code errors: results in an error:
```rust,ignore ```rust,ignore
let mut s = String::from("hello"); let mut s = String::from("hello");
@@ -200,7 +209,8 @@ let r3 = &mut s; // BIG PROBLEM
Here’s the error: Here’s the error:
```text ```text
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable error[E0502]: cannot borrow `s` as mutable because it is also borrowed as
immutable
--> borrow_thrice.rs:6:19 --> borrow_thrice.rs:6:19
| |
4 | let r1 = &s; // no problem 4 | let r1 = &s; // no problem
@@ -214,24 +224,24 @@ error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immuta
Whew! We *also* cannot have a mutable reference while we have an immutable one. Whew! We *also* cannot have a mutable reference while we have an immutable one.
Users of an immutable reference don’t expect the values to suddenly change out Users of an immutable reference don’t expect the values to suddenly change out
from under them! Multiple immutable references are okay, however, since no one from under them! However, multiple immutable references are okay because no one
who is just reading the data has the ability to affect anyone else’s reading of who is just reading the data has the ability to affect anyone else’s reading of
the data. the data.
Even though these errors may be frustrating at times, remember that it’s the Even though these errors may be frustrating at times, remember that it’s the
Rust compiler pointing out a potential bug earlier (at compile time rather than Rust compiler pointing out a potential bug early (at compile time rather than
at runtime) and showing you exactly where the problem is instead of you having at runtime) and showing you exactly where the problem is instead of you having
to track down why sometimes your data isn’t what you thought it should be. to track down why sometimes your data isn’t what you thought it should be.
### Dangling References ### Dangling References
In languages with pointers, it’s easy to make the error of creating a *dangling In languages with pointers, it’s easy to erroneously create a *dangling
pointer*, a pointer referencing a location in memory that may have been given pointer*, a pointer that references a location in memory that may have been
to someone else, by freeing some memory while keeping around a pointer to that given to someone else, by freeing some memory while preserving a pointer to
memory. In Rust, by contrast, the compiler guarantees that references will that memory. In Rust, by contrast, the compiler guarantees that references will
never be dangling: if we have a reference to some data, the compiler will never be dangling references: if we have a reference to some data, the compiler
ensure that the data will not go out of scope before the reference to the data will ensure that the data will not go out of scope before the reference to the
does. data does.
Let’s try to create a dangling reference: Let’s try to create a dangling reference:
@@ -265,17 +275,17 @@ error[E0106]: missing lifetime specifier
error: aborting due to previous error error: aborting due to previous error
``` ```
This error message refers to a feature we haven’t learned about yet: This error message refers to a feature we haven’t covered yet: *lifetimes*.
*lifetimes*. We’ll discuss lifetimes in detail in Chapter 10, but, disregarding We’ll discuss lifetimes in detail in Chapter 10. But, if you disregard the
the parts about lifetimes, the message does contain the key to why this code is parts about lifetimes, the message does contain the key to why this code is a
a problem: problem:
```text ```text
this function's return type contains a borrowed value, but there is no value this function's return type contains a borrowed value, but there is no value
for it to be borrowed from. for it to be borrowed from.
``` ```
Let’s have a closer look at exactly what’s happening at each stage of our Let’s take a closer look at exactly what’s happening at each stage of our
`dangle` code: `dangle` code:
```rust,ignore ```rust,ignore
@@ -288,10 +298,10 @@ fn dangle() -> &String { // dangle returns a reference to a String
// Danger! // Danger!
``` ```
Because `s` is created inside of `dangle`, when the code of `dangle` is Because `s` is created inside `dangle`, when the code of `dangle` is finished,
finished, it will be deallocated. But we tried to return a reference to it. `s` will be deallocated. But we tried to return a reference to it. That means
That means this reference would be pointing to an invalid `String`! That’s no this reference would be pointing to an invalid `String`! That’s no good. Rust
good. Rust won’t let us do this. won’t let us do this.
The correct code here is to return the `String` directly: The correct code here is to return the `String` directly:
@@ -303,15 +313,16 @@ fn no_dangle() -> String {
} }
``` ```
This works, no problem. Ownership is moved out, nothing is deallocated. This works without any problems. Ownership is moved out, and nothing is
deallocated.
### The Rules of References ### The Rules of References
Here’s a recap of what we’ve talked about: Let’s recap what we’ve discussed about references:
1. At any given time, you may have *either*, but not both of: 1. At any given time, you can have *either* but not both of:
1. One mutable reference. * One mutable reference.
2. Any number of immutable references. * Any number of immutable references.
2. References must always be valid. 2. References must always be valid.
Next, let’s look at a different kind of reference: slices. Next, we’ll look at a different kind of reference: slices.
+108 -87
View File
@@ -1,13 +1,13 @@
## Slices ## Slices
There is another data type which does not have ownership: slices. Slices let Another data type that does not have ownership is the *slice*. Slices let you
you reference a contiguous sequence of elements in a collection rather than the reference a contiguous sequence of elements in a collection rather than the
whole collection itself. whole collection.
Here’s a small programming problem: write a function which takes a string and Here’s a small programming problem: write a function that takes a string and
returns the first word it finds in that string. If it doesn’t find a space in returns the first word it finds in that string. If the function doesn’t find a
the string, it means the whole string is one word, so the whole thing should be space in the string, it means the whole string is one word, so the entire
returned. string should be returned.
Let’s think about the signature of this function: Let’s think about the signature of this function:
@@ -17,9 +17,10 @@ fn first_word(s: &String) -> ?
This function, `first_word`, takes a `&String` as an argument. We don’t want This function, `first_word`, takes a `&String` as an argument. We don’t want
ownership, so this is fine. But what should we return? We don’t really have a ownership, so this is fine. But what should we return? We don’t really have a
way to talk about *part* of a string. We could return the index of the end of way to talk about *part* of a string. However, we could return the index of the
the word, though. Let’s try that: end of the word. Let’s try that as shown in Listing 4-10:
<figure>
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
```rust ```rust
@@ -36,30 +37,39 @@ fn first_word(s: &String) -> usize {
} }
``` ```
Let’s break that down a bit: <figcaption>
Listing 4-10: The `first_word` function that returns a byte index value into
the `String` argument
</figcaption>
</figure>
Let’s break down this code a bit:
```rust,ignore ```rust,ignore
let bytes = s.as_bytes(); let bytes = s.as_bytes();
``` ```
Since we need to go through the String element by element and check if a value Because we need to go through the `String` element by element and check whether
is a space, we will convert our String to an array of bytes using the a value is a space, we’ll convert our `String` to an array of bytes using the
`as_bytes` method. `as_bytes` method:
```rust,ignore ```rust,ignore
for (i, &item) in bytes.iter().enumerate() { for (i, &item) in bytes.iter().enumerate() {
``` ```
We will be discussing iterators in more detail in Chapter 16, but for now, know We’ll discuss iterators in more detail in Chapter 16. For now, know that `iter`
that `iter` is a method that returns each element in a collection, and is a method that returns each element in a collection, and `enumerate` wraps
`enumerate` wraps the result of `iter` and returns each element as part of a the result of `iter` and returns each element as part of a tuple instead. The
tuple instead, where the first element of the tuple is the index, and the first element of the returned tuple is the index, and the second element is a
second element is a reference to the element itself. This is a bit nicer than reference to the element. This is a bit more convenient than calculating the
calculating the index ourselves. index ourselves.
Since it’s a tuple, we can use patterns, just like elsewhere in Rust. So we Because the method returns a tuple, we can use patterns, just like everywhere
match against the tuple with `i` for the index and `&item` for a single byte. else in Rust. So we match against the tuple with `i` for the index and `&item`
Since we get a reference from `.iter().enumerate()`, we use `&` in the pattern. for a single byte. Because we get a reference from `.iter().enumerate()`, we
use `&` in the pattern:
```rust,ignore ```rust,ignore
if item == b' ' { if item == b' ' {
@@ -69,17 +79,18 @@ Since we get a reference from `.iter().enumerate()`, we use `&` in the pattern.
s.len() s.len()
``` ```
We search for the byte that represents the space, using the byte literal We search for the byte that represents the space by using the byte literal
syntax. If we find a space, we return the position. Otherwise, we return the syntax. If we find a space, we return the position. Otherwise, we return the
length of the string, using `s.len()`. length of the string by using `s.len()`.
We now have a way to find out the index of the end of the first word in the We now have a way to find out the index of the end of the first word in the
string, but there’s a problem. We’re returning a `usize` on its own, but it’s string, but there’s a problem. We’re returning a `usize` on its own, but it’s
only a meaningful number in the context of the `&String`. In other words, only a meaningful number in the context of the `&String`. In other words,
because it’s a separate value from the `String`, there’s no guarantee that it because it’s a separate value from the `String`, there’s no guarantee that it
will still be valid in the future. Consider this program that uses this will still be valid in the future. Consider the program in Listing 4-11 that
`first_word` function: uses the `first_word` function from Listing 4-10:
<figure>
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
```rust ```rust
@@ -102,34 +113,43 @@ fn main() {
s.clear(); // This empties the String, making it equal to "". s.clear(); // This empties the String, making it equal to "".
// word still has the value 5 here, but there’s no more string that // word still has the value 5 here, but there's no more string that
// we could meaningfully use the value 5 with. word is now totally invalid! // we could meaningfully use the value 5 with. word is now totally invalid!
} }
``` ```
This program compiles without any errors, and also would if we used `word` <figcaption>
after calling `s.clear()`. `word` isn’t connected to the state of `s` at all,
so `word` still contains the value `5`. We could use that value `5` with the
variable `s` to try to extract the first word out, but this would be a bug
since the contents of `s` have changed since we saved `5` in `word`.
This is bad! It’s even worse if we wanted to write a `second_word` function. Listing 4-11: Storing the result from calling the `first_word` function then
Its signature would have to look like this: changing the `String` contents
</figcaption>
</figure>
This program compiles without any errors and also would if we used `word` after
calling `s.clear()`. `word` isn’t connected to the state of `s` at all, so
`word` still contains the value `5`. We could use that value `5` with the
variable `s` to try to extract the first word out, but this would be a bug
because the contents of `s` have changed since we saved `5` in `word`.
Having to worry about the index in `word` getting out of sync with the data in
`s` is tedious and error prone! Managing these indices is even more brittle if
we write a `second_word` function. Its signature would have to look like this:
```rust,ignore ```rust,ignore
fn second_word(s: &String) -> (usize, usize) { fn second_word(s: &String) -> (usize, usize) {
``` ```
Now we’re tracking both a start *and* an ending index, and we have even more Now we’re tracking a start *and* an ending index, and we have even more values
values that were calculated from data in a particular state but aren’t tied to that were calculated from data in a particular state but aren’t tied to that
that state at all. We now have three unrelated variables floating around which state at all. We now have three unrelated variables floating around that need
need to be kept in sync. to be kept in sync.
Luckily, Rust has a solution to this problem: string slices. Luckily, Rust has a solution to this problem: string slices.
### String Slices ### String Slices
A string slice is a reference to part of a `String`, and looks like this: A *string slice* is a reference to part of a `String`, and looks like this:
```rust ```rust
let s = String::from("hello world"); let s = String::from("hello world");
@@ -138,7 +158,7 @@ let hello = &s[0..5];
let world = &s[6..11]; let world = &s[6..11];
``` ```
This is similar to taking a reference to the whole `String`, but with the extra This is similar to taking a reference to the whole `String` but with the extra
`[0..5]` bit. Rather than a reference to the entire `String`, it’s a reference `[0..5]` bit. Rather than a reference to the entire `String`, it’s a reference
to an internal position in the `String` and the number of elements that it to an internal position in the `String` and the number of elements that it
refers to. refers to.
@@ -148,20 +168,20 @@ slice data structure actually stores the starting position and the length of
the slice. So in the case of `let world = &s[6..11];`, `world` would be a slice the slice. So in the case of `let world = &s[6..11];`, `world` would be a slice
that contains a pointer to the 6th byte of `s` and a length value of 5. that contains a pointer to the 6th byte of `s` and a length value of 5.
Figure 4-6 shows this in a diagram: Figure 4-12 shows this in a diagram.
<figure> <figure>
<img alt="world containing a pointer to the 6th byte of String s and a length 5" src="img/trpl04-06.svg" class="center" style="width: 50%;" /> <img alt="world containing a pointer to the 6th byte of String s and a length 5" src="img/trpl04-06.svg" class="center" style="width: 50%;" />
<figcaption> <figcaption>
Figure 4-6: String slice referring to part of a `String` Figure 4-12: String slice referring to part of a `String`
</figcaption> </figcaption>
</figure> </figure>
With Rust’s `..` range syntax, if you want to start at the first index (zero), With Rust’s `..` range syntax, if you want to start at the first index (zero),
you can drop the value before the `..`. In other words, these are equal: you can drop the value before the two periods. In other words, these are equal:
```rust ```rust
let s = String::from("hello"); let s = String::from("hello");
@@ -170,8 +190,8 @@ let slice = &s[0..2];
let slice = &s[..2]; let slice = &s[..2];
``` ```
By the same token, if your slice should include the last byte of the `String`, By the same token, if your slice includes the last byte of the `String`, you
you can drop the trailing number. That means these are equal: can drop the trailing number. That means these are equal:
```rust ```rust
let s = String::from("hello"); let s = String::from("hello");
@@ -194,8 +214,8 @@ let slice = &s[0..len];
let slice = &s[..]; let slice = &s[..];
``` ```
With this in mind, let’s re-write `first_word` to return a slice. The type that With all this information in mind, let’s rewrite `first_word` to return a
signifies “string slice” is written as `&str`: slice. The type that signifies “string slice” is written as `&str`:
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
@@ -213,10 +233,10 @@ fn first_word(s: &String) -> &str {
} }
``` ```
We get the index for the end of the word in the same way as before, by looking We get the index for the end of the word in the same way as we did in Listing
for the first occurrence of a space. When we find a space, we return a string 4-10, by looking for the first occurrence of a space. When we find a space, we
slice using the start of the string and the index of the space as the starting return a string slice using the start of the string and the index of the space
and ending indices. as the starting and ending indices.
Now when we call `first_word`, we get back a single value that is tied to the Now when we call `first_word`, we get back a single value that is tied to the
underlying data. The value is made up of a reference to the starting point of underlying data. The value is made up of a reference to the starting point of
@@ -228,13 +248,15 @@ Returning a slice would also work for a `second_word` function:
fn second_word(s: &String) -> &str { fn second_word(s: &String) -> &str {
``` ```
We now have a straightforward API that’s much harder to mess up. Remember our We now have a straightforward API that’s much harder to mess up, since the
bug from before, when we got the first word but then cleared the string so that compiler will ensure the references into the `String` remain valid. Remember
our first word was invalid? That code was logically incorrect but didn’t show the bug in the program in Listing 4-11, when we got the index to the end of the
any immediate errors. The problems would show up later, if we kept trying to first word but then cleared the string so our index was invalid? That code was
use the first word index with an emptied string. Slices make this bug logically incorrect but didn’t show any immediate errors. The problems would
impossible, and let us know we have a problem with our code much sooner. Using show up later if we kept trying to use the first word index with an emptied
the slice version of `first_word` will throw a compile time error: string. Slices make this bug impossible and let us know we have a problem with
our code much sooner. Using the slice version of `first_word` will throw a
compile time error:
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
@@ -266,45 +288,45 @@ fn main() {
^ ^
``` ```
Remember from the borrowing rules that if we have an immutable reference to Recall from the borrowing rules that if we have an immutable reference to
something, we cannot also take a mutable reference. Since `clear` needs to something, we cannot also take a mutable reference. Because `clear` needs to
truncate the `String`, it tries to take a mutable reference, which fails. Not truncate the `String`, it tries to take a mutable reference, which fails. Not
only has Rust made our API easier to use, but it’s also eliminated an entire only has Rust made our API easier to use, but it has also eliminated an entire
class of errors at compile time! class of errors at compile time!
#### String Literals are Slices #### String Literals Are Slices
Remember how we talked about string literals being stored inside of the binary Recall that we talked about string literals being stored inside the binary. Now
itself? Now that we know about slices, we can now properly understand string that we know about slices, we can properly understand string literals:
literals.
```rust ```rust
let s = "Hello, world!"; let s = "Hello, world!";
``` ```
The type of `s` here is `&str`: It’s a slice, pointing to that specific point The type of `s` here is `&str`: it’s a slice pointing to that specific point of
of the binary. This is also why string literals are immutable; `&str` is an the binary. This is also why string literals are immutable; `&str` is an
immutable reference. immutable reference.
#### String Slices as Arguments #### String Slices as Arguments
Knowing that you can take slices of both literals and `String`s leads us to one Knowing that you can take slices of literals and `String`s leads us to one more
more improvement on `first_word`, and that’s its signature: improvement on `first_word`, and that’s its signature:
```rust,ignore ```rust,ignore
fn first_word(s: &String) -> &str { fn first_word(s: &String) -> &str {
``` ```
A more experienced Rustacean would write this one instead because it allows us A more experienced Rustacean would write the following line instead because it
to use the same function on both `String`s and `&str`s: allows us to use the same function on both `String`s and `&str`s:
```rust,ignore ```rust,ignore
fn first_word(s: &str) -> &str { fn first_word(s: &str) -> &str {
``` ```
If we have a string slice, we can pass that as the argument directly. If we If we have a string slice, we can pass that as the argument directly. If we
have a `String`, we can pass a slice of the entire `String`. This makes our API have a `String`, we can pass a slice of the entire `String`. Defining a
more general and useful without losing any functionality: function to take a string slice argument instead of a reference to a String
makes our API more general and useful without losing any functionality:
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
@@ -346,8 +368,8 @@ more general slice type, too. Consider this array:
let a = [1, 2, 3, 4, 5]; let a = [1, 2, 3, 4, 5];
``` ```
Just like we may want to refer to a part of a string, we may want to refer to Just like we might want to refer to a part of a string, we might want to refer
part of an array, and would do so like this: to part of an array and would do so like this:
```rust ```rust
let a = [1, 2, 3, 4, 5]; let a = [1, 2, 3, 4, 5];
@@ -355,20 +377,19 @@ let a = [1, 2, 3, 4, 5];
let slice = &a[1..3]; let slice = &a[1..3];
``` ```
This slice has the type `&[i32]`. It works the exact same way as string slices This slice has the type `&[i32]`. It works the same way as string slices do, by
do, by storing a reference to the first element and a length. You’ll use this storing a reference to the first element and a length. You’ll use this kind of
kind of slice for all sorts of other collections. We’ll discuss these in detail slice for all sorts of other collections. We’ll discuss these collections in
when we talk about vectors in Chapter 8. detail when we talk about vectors in Chapter 8.
## Summary ## Summary
The concepts of ownership, borrowing, and slices are what ensure memory safety The concepts of ownership, borrowing, and slices are what ensure memory safety
in Rust programs at compile time. Rust is a language that gives you control in Rust programs at compile time. The Rust language gives you control over your
over your memory usage like other systems programming languages, but having the memory usage like other systems programming languages, but having the owner of
owner of data automatically clean up that data when the owner goes out of scope data automatically clean up that data when the owner goes out of scope means
means you don’t have to write and debug extra code to get this control. you don’t have to write and debug extra code to get this control.
Ownership affects how lots of other parts of Rust work, so we will be talking Ownership affects how lots of other parts of Rust work, so we’ll talk about
about these concepts further throughout the rest of the book. Let’s move on to these concepts further throughout the rest of the book. Let’s move on to the
the next chapter where we’ll look at grouping pieces of data together in a next chapter and look at grouping pieces of data together in a `struct`.
`struct`.
+4 -3
View File
@@ -13,6 +13,7 @@
<xsl:template match="w:p[w:pPr/w:pStyle/@w:val = 'ChapterStart']" /> <xsl:template match="w:p[w:pPr/w:pStyle/@w:val = 'ChapterStart']" />
<xsl:template match="w:p[w:pPr/w:pStyle/@w:val = 'Normal']" /> <xsl:template match="w:p[w:pPr/w:pStyle/@w:val = 'Normal']" />
<xsl:template match="w:p[w:pPr/w:pStyle/@w:val = 'Standard']" />
<!-- Paragraph styles --> <!-- Paragraph styles -->
@@ -71,7 +72,7 @@
<xsl:text>&#10;&#10;</xsl:text> <xsl:text>&#10;&#10;</xsl:text>
</xsl:template> </xsl:template>
<xsl:template match="w:p[w:pPr/w:pStyle[@w:val = 'BodyFirst' or @w:val = 'Body' or @w:val = 'BodyFirstBox' or @w:val = 'BodyBox']]"> <xsl:template match="w:p[w:pPr/w:pStyle[@w:val = 'BodyFirst' or @w:val = 'Body' or @w:val = 'BodyFirstBox' or @w:val = 'BodyBox' or @w:val = '1stPara']]">
<xsl:if test=".//w:t"> <xsl:if test=".//w:t">
<xsl:apply-templates select="*" /> <xsl:apply-templates select="*" />
<xsl:text>&#10;&#10;</xsl:text> <xsl:text>&#10;&#10;</xsl:text>
@@ -137,7 +138,7 @@ Unmatched: <xsl:value-of select="w:pPr/w:pStyle/@w:val" />
<!-- Character styles --> <!-- Character styles -->
<xsl:template match="w:r[w:rPr/w:rStyle[@w:val = 'Literal' or @w:val = 'LiteralBold' or @w:val = 'EmphasisBold']]"> <xsl:template match="w:r[w:rPr/w:rStyle[@w:val = 'Literal' or @w:val = 'LiteralBold' or @w:val = 'EmphasisBold' or @w:val = 'LiteralCaption']]">
<xsl:choose> <xsl:choose>
<xsl:when test="normalize-space(w:t) != ''"> <xsl:when test="normalize-space(w:t) != ''">
<xsl:if test="starts-with(w:t, ' ')"> <xsl:if test="starts-with(w:t, ' ')">
@@ -156,7 +157,7 @@ Unmatched: <xsl:value-of select="w:pPr/w:pStyle/@w:val" />
</xsl:choose> </xsl:choose>
</xsl:template> </xsl:template>
<xsl:template match="w:r[w:rPr/w:rStyle/@w:val = 'EmphasisItalic']"> <xsl:template match="w:r[w:rPr/w:rStyle[@w:val = 'EmphasisItalic' or @w:val = 'EmphasisItalicBox' or @w:val = 'EmphasisNote']]">
<xsl:choose> <xsl:choose>
<xsl:when test="normalize-space(w:t) != ''"> <xsl:when test="normalize-space(w:t) != ''">
<xsl:if test="starts-with(w:t, ' ')"> <xsl:if test="starts-with(w:t, ' ')">