diff options
Diffstat (limited to 'src/doc/book/nostarch/chapter04.md')
-rw-r--r-- | src/doc/book/nostarch/chapter04.md | 520 |
1 files changed, 207 insertions, 313 deletions
diff --git a/src/doc/book/nostarch/chapter04.md b/src/doc/book/nostarch/chapter04.md index cbcad103e..11f7f4944 100644 --- a/src/doc/book/nostarch/chapter04.md +++ b/src/doc/book/nostarch/chapter04.md @@ -16,21 +16,15 @@ features: borrowing, slices, and how Rust lays data out in memory. ## What Is Ownership? -*Ownership* is a set of rules that governs how a Rust program manages memory. +*Ownership* is a set of rules that govern how a Rust program manages memory. All programs have to manage the way they use a computer’s memory while running. -Some languages have garbage collection that regularly looks for no-longer used +Some languages have garbage collection that regularly looks for no-longer-used memory as the program runs; in other languages, the programmer must explicitly allocate and free the memory. Rust uses a third approach: memory is managed through a system of ownership with a set of rules that the compiler checks. If any of the rules are violated, the program won’t compile. None of the features of ownership will slow down your program while it’s running. -<!--- Minor nit: garbage collection isn't constant, it happens at times specified -by the collection algorithm. Maybe "Some languages have garbage collection that -regularly looks for no-longer used memory as the program runs." -/JT ---> -<!-- Took this suggestion! /Carol --> - Because ownership is a new concept for many programmers, it does take some time to get used to. The good news is that the more experienced you become with Rust and the rules of the ownership system, the easier you’ll find it to naturally @@ -44,92 +38,63 @@ strings. > ### The Stack and the Heap > > Many programming languages don’t require you to think about the stack and the -> heap very often. But in a systems programming language like Rust, whether a -> value is on the stack or the heap affects how the language behaves and why -> you have to make certain decisions. Parts of ownership will be described in -> relation to the stack and the heap later in this chapter, so here is a brief -> explanation in preparation. +heap very often. But in a systems programming language like Rust, whether a +value is on the stack or the heap affects how the language behaves and why you +have to make certain decisions. Parts of ownership will be described in +relation to the stack and the heap later in this chapter, so here is a brief +explanation in preparation. > > Both the stack and the heap are parts of memory available to your code to use -> at runtime, but they are structured in different ways. The stack stores -> values in the order it gets them and removes the values in the opposite -> order. 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 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*, and removing data is called *popping off the stack*. All -> data stored on the stack must have a known, fixed size. Data with an unknown -> size at compile time or a size that might change must be stored on the heap -> instead. +at runtime, but they are structured in different ways. The stack stores values +in the order it gets them and removes the values in the opposite order. 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 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*, and +removing data is called *popping off the stack*. All data stored on the stack +must have a known, fixed size. Data with an unknown size at compile time or a +size that might change must be stored on the heap instead. > > The heap is less organized: when you put data on the heap, you request a -> certain amount of space. The memory allocator finds an empty spot in the heap -> that is big enough, marks it as being in use, and returns a *pointer*, which -> is the address of that location. This process is called *allocating on the -> heap* and is sometimes abbreviated as just *allocating* (pushing values onto -> the stack is not considered allocating). Because the pointer to the heap is a -> known, fixed size, you can store the pointer on the stack, but when you want -> the actual data, you must follow the pointer. Think of being seated at a -> restaurant. When you enter, you state the number of people in your group, and -> the staff finds an empty table that fits everyone and leads you there. If -> someone in your group comes late, they can ask where you’ve been seated to -> find you. +certain amount of space. The memory allocator finds an empty spot in the heap +that is big enough, marks it as being in use, and returns a *pointer*, which is +the address of that location. This process is called *allocating on the heap* +and is sometimes abbreviated as just *allocating* (pushing values onto the +stack is not considered allocating). Because the pointer to the heap is a +known, fixed size, you can store the pointer on the stack, but when you want +the actual data, you must follow the pointer. Think of being seated at a +restaurant. When you enter, you state the number of people in your group, and +the host finds an empty table that fits everyone and leads you there. If +someone in your group comes late, they can ask where you’ve been seated to find +you. > > Pushing to the stack is faster than allocating on the heap because the -> allocator never has to search for a place to store new data; that location is -> always at the top of the stack. Comparatively, allocating space on the heap -> requires more work, because the allocator must first find a big enough space -> to hold the data and then perform bookkeeping to prepare for the next -> allocation. - -<!--- Minor nit: not sure if worth clarifying but thought I'd mention - performance -for heap allocation I think isn't as much the time spent in the allocator but that -you have to spend time asking the system for memory. Custom allocators still have to -do the allocation step but try to avoid the system step where possible. -/JT ---> -<!-- I think this is a bit in the weeds, not making any change here /Carol --> - +allocator never has to search for a place to store new data; that location is +always at the top of the stack. Comparatively, allocating space on the heap +requires more work because the allocator must first find a big enough space to +hold the data and then perform bookkeeping to prepare for the next allocation. +> > Accessing data in the heap is slower than accessing data on the stack because -> you have to follow a pointer to get there. Contemporary processors are faster -> if they jump around less in memory. Continuing the analogy, consider a server -> at a restaurant taking orders from many tables. It’s most efficient to get -> all the orders at one table before moving on to the next table. Taking an -> order from table A, then an order from table B, then one from A again, and -> then one from B again would be a much slower process. By the same token, a -> processor can do its job better if it works on data that’s close to other -> data (as it is on the stack) rather than farther away (as it can be on the -> heap). - -<!--- I don't quite understand the last sentence. If you allocate enough to create -virtual memory, sure. But modern systems you're probably safe for most things? Also, -if we're contrasting against something like the heap, just having the ability to allocate -large space is probably a big benefit of the heap rather than a drawback. IMHO I'd probably -just drop the last sentence. -/JT ---> -<!-- Done! /Carol --> - +you have to follow a pointer to get there. Contemporary processors are faster +if they jump around less in memory. Continuing the analogy, consider a server +at a restaurant taking orders from many tables. It’s most efficient to get all +the orders at one table before moving on to the next table. Taking an order +from table A, then an order from table B, then one from A again, and then one +from B again would be a much slower process. By the same token, a processor can +do its job better if it works on data that’s close to other data (as it is on +the stack) rather than farther away (as it can be on the heap). > > When your code calls a function, the values passed into the function -> (including, potentially, pointers to data on the heap) and the function’s -> local variables get pushed onto the stack. When the function is over, those -> values get popped off the stack. - -<!--- Some calling conventions don't always use the stack for parameters. -For example, Windows x64 calling convention puts the first 4 arguments into -registers, and only puts args 5 and later on the stack. Ditto for the return -value. If it can fit in a register, x64 will use that instead of the stack: - -https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention?view=msvc-170#parameter-passing -/JT ---> -<!-- I think this is a bit in the weeds, not making any change here /Carol --> - +(including, potentially, pointers to data on the heap) and the function’s local +variables get pushed onto the stack. When the function is over, those values +get popped 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 you 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 the main purpose of ownership -> is to manage heap data can help explain why it works the way it does. +minimizing the amount of duplicate data on the heap, and cleaning up unused +data on the heap so you 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 the main purpose of ownership +is to manage heap data can help explain why it works the way it does. ### Ownership Rules @@ -140,14 +105,6 @@ work through the examples that illustrate them: * There can only be one owner at a time. * When the owner goes out of scope, the value will be dropped. -<!--- Maybe splitting hairs, but for the first bullet I'd say: -"Each value in Rust has an *owner*". - -If we say variables here, and then find out later that, for example, structs can -also be owners, this gets a bit mirky. -/JT ---> -<!-- Took this suggestion! /Carol --> - ### Variable Scope Now that we’re past basic Rust syntax, we won’t include all the `fn main() {` @@ -170,8 +127,8 @@ which it’s declared until the end of the current *scope*. Listing 4-1 shows a program with comments annotating where the variable `s` would be valid. ``` -{ // s is not valid here, it’s not yet declared - let s = "hello"; // s is valid from this point forward. +{ // s is not valid here, since it's not yet declared + let s = "hello"; // s is valid from this point forward // do stuff with s } // this scope is now over, and s is no longer valid @@ -181,23 +138,23 @@ Listing 4-1: A variable and the scope in which it is valid In other words, there are two important points in time here: -* When `s` comes *into scope*, it is valid. -* It remains valid until it goes *out of scope*. +* When `s` comes *into* scope, it is valid. +* It remains valid until it goes *out of* scope. At this point, the relationship between scopes and when variables are valid is similar to that in other programming languages. Now we’ll build on top of this understanding by introducing the `String` type. -### The `String` Type +### The String Type To illustrate the rules of ownership, we need a data type that is more complex -than those we covered in the “Data Types” section of Chapter 3. The types -covered previously are all a known size, can be stored on the stack and popped -off the stack when their scope is over, and can be quickly and trivially copied -to make a new, independent instance if another part of code needs to use the -same value in a different scope. But we want to look at data that is stored on -the heap and explore how Rust knows when to clean up that data, and the -`String` type is a great example. +than those we covered in “Data Types” on page XX. The types covered previously +are of a known size, can be stored on the stack and popped off the stack when +their scope is over, and can be quickly and trivially copied to make a new, +independent instance if another part of code needs to use the same value in a +different scope. But we want to look at data that is stored on the heap and +explore how Rust knows when to clean up that data, and the `String` type is a +great example. We’ll concentrate on the parts of `String` that relate to ownership. These aspects also apply to other complex data types, whether they are provided by @@ -220,9 +177,9 @@ let s = String::from("hello"); The double colon `::` operator allows us to namespace this particular `from` function under the `String` type rather than using some sort of name like -`string_from`. We’ll discuss this syntax more in the “Method Syntax” section of -Chapter 5 and when we talk about namespacing with modules in “Paths for -Referring to an Item in the Module Tree” in Chapter 7. +`string_from`. We’ll discuss this syntax more in “Method Syntax” on page XX, +and when we talk about namespacing with modules in “Paths for Referring to an +Item in the Module Tree” on page XX. This kind of string *can* be mutated: @@ -231,11 +188,11 @@ let mut s = String::from("hello"); 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 -cannot? The difference is how these two types deal with memory. +cannot? The difference is in how these two types deal with memory. ### Memory and Allocation @@ -251,8 +208,8 @@ we need to allocate an amount of memory on the heap, unknown at compile time, to hold the contents. This means: * The memory must be requested from the memory allocator at runtime. -* We need a way of returning this memory to the allocator when we’re - done with our `String`. +* We need a way of returning this memory to the allocator when we’re done with +our `String`. 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 @@ -261,19 +218,13 @@ languages. However, the second part is different. In languages with a *garbage collector (GC)*, the GC keeps track of and cleans up memory that isn’t being used anymore, and we don’t need to think about it. In most languages without a GC, -it’s our responsibility to identify when memory is no longer being used and +it’s our responsibility to identify when memory is no longer being used and to call code to explicitly free it, just as we did to request it. Doing this correctly has historically been a difficult programming problem. If we forget, we’ll waste memory. If we do it too early, we’ll have an invalid variable. If we do it twice, that’s a bug too. We need to pair exactly one `allocate` with exactly one `free`. -<!--- The phrase "explicitly return it" gives a connotation in programming of -returning a value to a caller rather than the more casual returning it to the OS. -Maybe we can say "explicitly delete it" or "explicitly free it". -/JT ---> -<!-- Changed "return" to "free" /Carol --> - 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 from Listing 4-1 using a `String` instead of a string literal: @@ -294,23 +245,23 @@ and it’s where the author of `String` can put the code to return the memory. Rust calls `drop` automatically at the closing curly bracket. > Note: In C++, this pattern of deallocating resources at the end of an item’s -> lifetime is sometimes called *Resource Acquisition Is Initialization (RAII)*. -> The `drop` function in Rust will be familiar to you if you’ve used RAII -> patterns. +lifetime is sometimes called *Resource Acquisition Is Initialization* *(RAII)*. +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 Rust code is written. It may seem simple right now, but the behavior of code can be unexpected in more complicated situations when we want to have multiple variables use the data we’ve allocated on the heap. Let’s explore some of those situations now. -#### Ways Variables and Data Interact: Move +#### Variables and Data Interacting with Move Multiple variables can interact with the same data in different ways in Rust. Let’s look at an example using an integer in Listing 4-2. ``` - let x = 5; - let y = x; +let x = 5; +let y = x; ``` Listing 4-2: Assigning the integer value of variable `x` to `y` @@ -324,8 +275,8 @@ onto the stack. Now let’s look at the `String` version: ``` - let s1 = String::from("hello"); - let s2 = s1; +let s1 = String::from("hello"); +let s2 = s1; ``` This looks very similar, so we might assume that the way it works would be the @@ -338,38 +289,20 @@ the memory that holds the contents of the string, a length, and a capacity. This group of data is stored on the stack. On the right is the memory on the heap that holds the contents. -<img alt="String in memory" src="img/trpl04-01.svg" class="center" style="width: 50%;" /> - -<!--- This might be me being a bit nitpicky - when you show what the string looks like -in memory, we're showing indices for data pointed to by ptr. I have a bit of a knee-jerk -reaction here since we don't think of strings has having indices in Rust (because of UTF-8) -Not sure if it's well enough alone, or if it might be better for the ptr to point at -at cells of memory without giving them indices. - -Something like: - -[ptr | --] -> [h][e][l][l][o] -[len | 5] -[capacity | 5] -/JT ---> -<!-- I think this is a bit in the weeds, not making any change here /Carol --> - -Figure 4-1: Representation in memory of a `String` holding the value `"hello"` +Figure 4-1: Representation in memory of a `String` holding the value `"hello"` 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` are currently using. The capacity is the total amount of memory, in bytes, that the -`String` has received from the allocator. The difference between length -and capacity matters, but not in this context, so for now, it’s fine to ignore -the capacity. +`String` has received from the allocator. The difference between length and +capacity matters, but not in this context, so for now, it’s fine to ignore the +capacity. When we assign `s1` to `s2`, the `String` data is copied, meaning we copy the pointer, the length, and the capacity that are on the stack. We do not copy the data on the heap that the pointer refers to. In other words, the data representation in memory looks like Figure 4-2. -<img alt="s1 and s2 pointing to the same value" src="img/trpl04-02.svg" class="center" style="width: 50%;" /> - Figure 4-2: Representation in memory of the variable `s2` that has a copy of the pointer, length, and capacity of `s1` @@ -378,8 +311,6 @@ look like if Rust instead copied the heap data as well. If Rust did this, the operation `s2 = s1` could be very expensive in terms of runtime performance if the data on the heap were large. -<img alt="s1 and s2 to two places" src="img/trpl04-03.svg" class="center" style="width: 50%;" /> - Figure 4-3: Another possibility for what `s2 = s1` might do if Rust copied the heap data as well @@ -391,7 +322,7 @@ same memory. This is known as a *double free* error and is one of the memory safety bugs we mentioned previously. Freeing memory twice can lead to memory corruption, which can potentially lead to security vulnerabilities. -To ensure memory safety, after the line `let s2 = s1`, Rust considers `s1` as +To ensure memory safety, after the line `let s2 = s1;`, Rust considers `s1` as no longer valid. Therefore, Rust doesn’t need to free anything when `s1` goes out of scope. Check out what happens when you try to use `s1` after `s2` is created; it won’t work: @@ -400,7 +331,7 @@ created; it won’t work: let s1 = String::from("hello"); let s2 = s1; -println!("{}, world!", s1); +println!("{s1}, world!"); ``` You’ll get an error like this because Rust prevents you from using the @@ -411,33 +342,32 @@ error[E0382]: borrow of moved value: `s1` --> src/main.rs:5:28 | 2 | let s1 = String::from("hello"); - | -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait + | -- move occurs because `s1` has type `String`, which + does not implement the `Copy` trait 3 | let s2 = s1; | -- value moved here 4 | -5 | println!("{}, world!", s1); - | ^^ value borrowed here after move +5 | println!("{s1}, world!"); + | ^^ value borrowed here after move ``` 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 without copying the data probably sounds like making a shallow copy. But -because Rust also invalidates the first variable, instead of calling it a -shallow copy, it’s known as a *move*. In this example, we would say that -`s1` was *moved* into `s2`. So what actually happens is shown in Figure 4-4. - -<img alt="s1 moved to s2" src="img/trpl04-04.svg" class="center" style="width: 50%;" /> +because Rust also invalidates the first variable, instead of being called a +shallow copy, it’s known as a *move*. In this example, we would say that `s1` +was *moved* into `s2`. So, what actually happens is shown in Figure 4-4. 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. 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* copying can be assumed to be inexpensive in terms of runtime performance. -#### Ways Variables and Data Interact: Clone +#### Variables and Data Interacting with Clone If we *do* want to deeply copy the heap data of the `String`, not just the stack data, we can use a common method called `clone`. We’ll discuss method @@ -450,7 +380,7 @@ Here’s an example of the `clone` method in action: let s1 = String::from("hello"); let s2 = s1.clone(); -println!("s1 = {}, s2 = {}", s1, s2); +println!("s1 = {s1}, s2 = {s2}"); ``` This works just fine and explicitly produces the behavior shown in Figure 4-3, @@ -462,14 +392,14 @@ different is going on. #### Stack-Only Data: Copy -There’s another wrinkle we haven’t talked about yet. This code using integers – -part of which was shown in Listing 4-2 – works and is valid: +There’s another wrinkle we haven’t talked about yet. This code using +integers—part of which was shown in Listing 4-2—works and is valid: ``` let x = 5; let y = x; -println!("x = {}, y = {}", x, y); +println!("x = {x}, y = {y}"); ``` But this code seems to contradict what we just learned: we don’t have a call to @@ -480,7 +410,7 @@ time are stored entirely on the stack, so copies of the actual values are quick to make. That means there’s no reason we would want to prevent `x` from being valid after we create the variable `y`. In other words, there’s no difference between deep and shallow copying here, so calling `clone` wouldn’t do anything -different from the usual shallow copying and we can leave it out. +different 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 types that are stored on the stack, as integers are (we’ll talk more about @@ -488,29 +418,13 @@ traits in Chapter 10). If a type implements the `Copy` trait, variables that use it do not move, but rather are trivially copied, making them still valid after assignment to another variable. -<!--- an older variable that uses that type, we mean? /LC ---> -<!-- I removed "older" here, I don't think that was quite right-- this sentence -is trying to describe the line `let y = x` where the variable `x` is assigned -to `y`. The variables must be the same type because they're getting the same -value, so "that uses that type" isn't relevant. Let me know if there's any -aspects that are still confusing here. /Carol --> -<!-- JT, is this all clear in the text? /LC --> -<!--- I think this is fine. When I teach it, I tend to stress *move* and *copy* -so that they can build up that framework. So my slight tweak to the above might -be: - -"If a type implements the `Copy` trait, variables that use it do not move but rather are -trivially copied, making them still valid after assignment to another variable." -/JT ---> -<!-- Took this suggestion! /Carol --> - Rust won’t let us annotate a type with `Copy` if the type, or any of its parts, has implemented the `Drop` trait. If the type needs something special to happen when the value goes out of scope and we add the `Copy` annotation to that type, we’ll get a compile-time error. To learn about how to add the `Copy` annotation -to your type to implement the trait, see “Derivable Traits” in Appendix C. +to your type to implement the trait, see “Derivable Traits” on page XX. -So what types implement the `Copy` trait? You can check the documentation for +So, what types implement the `Copy` trait? You can check the documentation for the given type to be sure, but as a general rule, any group of simple scalar values can implement `Copy`, and nothing that requires allocation or is some form of resource can implement `Copy`. Here are some of the types that @@ -518,10 +432,10 @@ implement `Copy`: * All the integer types, such as `u32`. * The Boolean type, `bool`, with values `true` and `false`. -* All the floating point types, such as `f64`. +* All the floating-point types, such as `f64`. * The character type, `char`. * Tuples, if they only contain types that also implement `Copy`. For example, - `(i32, i32)` implements `Copy`, but `(i32, String)` does not. +`(i32, i32)` implements `Copy`, but `(i32, String)` does not. ### Ownership and Functions @@ -530,9 +444,8 @@ assigning a value to a variable. Passing a variable to a function will move or copy, just as assignment does. Listing 4-3 has an example with some annotations showing where variables go into and out of scope. -Filename: src/main.rs - ``` +// src/main.rs fn main() { let s = String::from("hello"); // s comes into scope @@ -545,17 +458,17 @@ fn main() { // but i32 is Copy, so it's okay to still // use x afterward -} // Here, x goes out of scope, then s. But because s's value was moved, nothing - // special happens. +} // Here, x goes out of scope, then s. However, because s's value was moved, + // nothing special happens fn takes_ownership(some_string: String) { // some_string comes into scope - println!("{}", some_string); + println!("{some_string}"); } // Here, some_string goes out of scope and `drop` is called. The backing - // memory is freed. + // memory is freed fn makes_copy(some_integer: i32) { // some_integer comes into scope - println!("{}", some_integer); -} // Here, some_integer goes out of scope. Nothing special happens. + println!("{some_integer}"); +} // Here, some_integer goes out of scope. Nothing special happens ``` Listing 4-3: Functions with ownership and scope annotated @@ -567,13 +480,12 @@ the ownership rules prevent you from doing so. ### Return Values and Scope -Returning values can also transfer ownership. Listing 4-4 shows an example -of a function that returns some value, with similar annotations as those in -Listing 4-3. - -Filename: src/main.rs +Returning values can also transfer ownership. Listing 4-4 shows an example of a +function that returns some value, with similar annotations as those in Listing +4-3. ``` +// src/main.rs fn main() { let s1 = gives_ownership(); // gives_ownership moves its return // value into s1 @@ -584,7 +496,7 @@ fn main() { // takes_and_gives_back, which also // moves its return value into s3 } // Here, s3 goes out of scope and is dropped. s2 was moved, so nothing - // happens. s1 goes out of scope and is dropped. + // happens. s1 goes out of scope and is dropped fn gives_ownership() -> String { // gives_ownership will move its // return value into the function @@ -597,7 +509,7 @@ fn gives_ownership() -> String { // gives_ownership will move its // function } -// This function takes a String and returns one +// This function takes a String and returns a String fn takes_and_gives_back(a_string: String) -> String { // a_string comes into // scope @@ -628,7 +540,7 @@ fn main() { let (s2, len) = calculate_length(s1); - println!("The length of '{}' is {}.", s2, len); + println!("The length of '{s2}' is {len}."); } fn calculate_length(s: String) -> (String, usize) { @@ -655,12 +567,6 @@ the data stored at that address; that data is owned by some other variable. Unlike a pointer, a reference is guaranteed to point to a valid value of a particular type for the life of that reference. -<!--- Possible wording tweak: "a reference is guaranteed to point to a valid value of a -particular type for the life of that reference" or "a reference is always guaranteed -to point to a valid value of a particular type" -/JT ---> -<!-- Took this suggestion! /Carol --> - Here is how you would define and use a `calculate_length` function that has a reference to an object as a parameter instead of taking ownership of the value: @@ -672,7 +578,7 @@ fn main() { let len = calculate_length(&s1); - println!("The length of '{}' is {}.", s1, len); + println!("The length of '{s1}' is {len}."); } fn calculate_length(s: &String) -> usize { @@ -686,14 +592,12 @@ function return value is gone. Second, note that we pass `&s1` into `String`. These ampersands represent *references*, and they allow you to refer to some value without taking ownership of it. Figure 4-5 depicts this concept. -<img alt="&String s pointing at String s1" src="img/trpl04-05.svg" class="center" /> - Figure 4-5: A diagram of `&String s` pointing at `String s1` > Note: The opposite of referencing by using `&` is *dereferencing*, which is -> accomplished with the dereference operator, `*`. We’ll see some uses of the -> dereference operator in Chapter 8 and discuss details of dereferencing in -> Chapter 15. +accomplished with the dereference operator, `*`. We’ll see some uses of the +dereference operator in Chapter 8 and discuss details of dereferencing in +Chapter 15. Let’s take a closer look at the function call here: @@ -714,12 +618,12 @@ the parameter `s` is a reference. Let’s add some explanatory annotations: fn calculate_length(s: &String) -> usize { // s is a reference to a String s.len() } // Here, s goes out of scope. But because it does not have ownership of what - // it refers to, it is not dropped. + // it refers to, the String is not dropped ``` The scope in which the variable `s` is valid is the same as any function parameter’s scope, but the value pointed to by the reference is not dropped -when `s` stops being used because `s` doesn’t have ownership. When functions +when `s` stops being used, because `s` doesn’t have ownership. When functions have references as parameters instead of the actual values, we won’t need to return the values in order to give back ownership, because we never had ownership. @@ -728,7 +632,7 @@ We call the action of creating a reference *borrowing*. As in real life, if a person owns something, you can borrow it from them. When you’re done, you have to give it back. You don’t own it. -So what happens if we try to modify something we’re borrowing? Try the code in +So, what happens if we try to modify something we’re borrowing? Try the code in Listing 4-6. Spoiler alert: it doesn’t work! Filename: src/main.rs @@ -750,13 +654,16 @@ Listing 4-6: Attempting to modify a borrowed value Here’s the error: ``` -error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference +error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` +reference --> src/main.rs:8:5 | 7 | fn change(some_string: &String) { - | ------- help: consider changing this to be a mutable reference: `&mut String` + | ------- help: consider changing this to be a mutable +reference: `&mut String` 8 | some_string.push_str(", world"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `some_string` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `some_string` is a `&` reference, so +the data it refers to cannot be borrowed as mutable ``` Just as variables are immutable by default, so are references. We’re not @@ -781,7 +688,7 @@ fn change(some_string: &mut String) { } ``` -First, we change `s` to be `mut`. Then we create a mutable reference with `&mut +First we change `s` to be `mut`. Then we create a mutable reference with `&mut s` where we call the `change` function, and update the function signature to accept a mutable reference with `some_string: &mut String`. This makes it very clear that the `change` function will mutate the value it borrows. @@ -790,22 +697,15 @@ Mutable references have one big restriction: if you have a mutable reference to a value, you can have no other references to that value. This code that attempts to create two mutable references to `s` will fail: -<!--- Clarification: "Mutable references have one big restriction: if you have a -mutable reference to a value, you can have no other references to that value." -This covers both not having two mutable references and having a mutable references -and an immutable reference to the same value. -/JT ---> -<!-- Took this suggestion! /Carol --> - Filename: src/main.rs ``` - let mut s = String::from("hello"); +let mut s = String::from("hello"); - let r1 = &mut s; - let r2 = &mut s; +let r1 = &mut s; +let r2 = &mut s; - println!("{}, {}", r1, r2); +println!("{r1}, {r2}"); ``` Here’s the error: @@ -819,8 +719,8 @@ error[E0499]: cannot borrow `s` as mutable more than once at a time 5 | let r2 = &mut s; | ^^^^^^ second mutable borrow occurs here 6 | -7 | println!("{}, {}", r1, r2); - | -- first borrow later used here +7 | println!("{r1}, {r2}"); + | -- first borrow later used here ``` This error says that this code is invalid because we cannot borrow `s` as @@ -831,7 +731,7 @@ in `r2` that borrows the same data as `r1`. The restriction preventing multiple mutable references to the same data at the same time allows for mutation but in a very controlled fashion. It’s something -that new Rustaceans struggle with, because most languages let you mutate +that new Rustaceans struggle with because most languages let you mutate whenever you’d like. The benefit of having this restriction is that Rust can prevent data races at compile time. A *data race* is similar to a race condition and happens when these three behaviors occur: @@ -841,8 +741,8 @@ condition and happens when these three behaviors occur: * 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 -when you’re trying to track them down at runtime; Rust prevents this problem -by refusing to compile code with data races! +when you’re trying to track them down at runtime; Rust prevents this problem by +refusing to compile code with data races! As always, we can use curly brackets to create a new scope, allowing for multiple mutable references, just not *simultaneous* ones: @@ -852,7 +752,7 @@ let mut s = String::from("hello"); { let r1 = &mut s; -} // r1 goes out of scope here, so we can make a new reference with no problems. +} // r1 goes out of scope here, so we can make a new reference with no problems let r2 = &mut s; ``` @@ -867,13 +767,14 @@ let r1 = &s; // no problem let r2 = &s; // no problem let r3 = &mut s; // BIG PROBLEM -println!("{}, {}, and {}", r1, r2, r3); +println!("{r1}, {r2}, and {r3}"); ``` Here’s the error: ``` -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 --> src/main.rs:6:14 | 4 | let r1 = &s; // no problem @@ -882,8 +783,8 @@ error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immuta 6 | let r3 = &mut s; // BIG PROBLEM | ^^^^^^ mutable borrow occurs here 7 | -8 | println!("{}, {}, and {}", r1, r2, r3); - | -- immutable borrow later used here +8 | println!("{r1}, {r2}, and {r3}"); + | -- immutable borrow later used here ``` Whew! We *also* cannot have a mutable reference while we have an immutable one @@ -904,20 +805,18 @@ let mut s = String::from("hello"); let r1 = &s; // no problem let r2 = &s; // no problem -println!("{} and {}", r1, r2); +println!("{r1} and {r2}"); // variables r1 and r2 will not be used after this point let r3 = &mut s; // no problem -println!("{}", r3); +println!("{r3}"); ``` The scopes of the immutable references `r1` and `r2` end after the `println!` where they are last used, which is before the mutable reference `r3` is -created. These scopes don’t overlap, so this code is allowed. The ability of -the compiler to tell that a reference is no longer being used at a point before -the end of the scope is called *Non-Lexical Lifetimes* (NLL for short), and you -can read more about it in The Edition Guide at -*https://doc.rust-lang.org/edition-guide/rust-2018/ownership-and-lifetimes/non-lexical-lifetimes.html*. +created. These scopes don’t overlap, so this code is allowed: the compiler can +tell that the reference is no longer being used at a point before the end of +the scope. Even though borrowing errors may be frustrating at times, remember that it’s the Rust compiler pointing out a potential bug early (at compile time rather @@ -927,9 +826,9 @@ have to track down why your data isn’t what you thought it was. ### Dangling References In languages with pointers, it’s easy to erroneously create a *dangling -pointer*--a pointer that references a location in memory that may have been -given to someone else--by freeing some memory while preserving a pointer to -that memory. In Rust, by contrast, the compiler guarantees that references will +pointer*—a pointer that references a location in memory that may have been +given to someone else—by freeing some memory while preserving a pointer to that +memory. In Rust, by contrast, the compiler guarantees that references will never be dangling references: if you have a reference to some data, the compiler will ensure that the data will not go out of scope before the reference to the data does. @@ -960,7 +859,8 @@ error[E0106]: missing lifetime specifier 5 | fn dangle() -> &String { | ^ expected named lifetime parameter | - = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from + = help: this function's return type contains a borrowed value, +but there is no value for it to be borrowed from help: consider using the `'static` lifetime | 5 | fn dangle() -> &'static String { @@ -972,22 +872,21 @@ discuss lifetimes in detail in Chapter 10. But, if you disregard the parts about lifetimes, the message does contain the key to why this code is a problem: ``` -this function's return type contains a borrowed value, but there is no value -for it to be borrowed from +this function's return type contains a borrowed value, but there +is no value for it to be borrowed from ``` Let’s take a closer look at exactly what’s happening at each stage of our `dangle` code: -Filename: src/main.rs - ``` +// src/main.rs fn dangle() -> &String { // dangle returns a reference to a String let s = String::from("hello"); // s is a new String &s // we return a reference to the String, s -} // Here, s goes out of scope, and is dropped. Its memory goes away. +} // Here, s goes out of scope and is dropped, so its memory goes away // Danger! ``` @@ -1014,7 +913,7 @@ deallocated. Let’s recap what we’ve discussed about references: * At any given time, you can have *either* one mutable reference *or* any - number of immutable references. +number of immutable references. * References must always be valid. Next, we’ll look at a different kind of reference: slices. @@ -1030,12 +929,6 @@ words separated by spaces and returns the first word it finds in that string. If the function doesn’t find a space in the string, the whole string must be one word, so the entire string should be returned. -<!--- Do we want to clarify this is for words separated by spaces? -Not all languages use spaces to separate words: -https://www.w3.org/International/articles/typography/linebreak.en#whatisword -/JT ---> -<!-- Took this suggestion! /Carol --> - Let’s work through how we’d write the signature of this function without using slices, to understand the problem that slices will solve: @@ -1052,15 +945,15 @@ Filename: src/main.rs ``` fn first_word(s: &String) -> usize { - [1] let bytes = s.as_bytes(); + 1 let bytes = s.as_bytes(); - for (i, &item)[2] in bytes.iter()[3].enumerate() { - [4] if item == b' ' { + for (2 i, &item) in 3 bytes.iter().enumerate() { + 4 if item == b' ' { return i; } } - [5] s.len() + 5 s.len() } ``` @@ -1071,13 +964,13 @@ Because we need to go through the `String` element by element and check whether a value is a space, we’ll convert our `String` to an array of bytes using the `as_bytes` method [1]. -Next, we create an iterator over the array of bytes using the `iter` method [3]. -We’ll discuss iterators in more detail in Chapter 13. For now, know that `iter` -is a method that returns each element in a collection and that `enumerate` -wraps the result of `iter` and returns each element as part of a tuple instead. -The first element of the tuple returned from `enumerate` is the index, and the -second element is a reference to the element. This is a bit more convenient -than calculating the index ourselves. +Next, we create an iterator over the array of bytes using the `iter` method +[3]. We’ll discuss iterators in more detail in Chapter 13. For now, know that +`iter` is a method that returns each element in a collection and that +`enumerate` wraps the result of `iter` and returns each element as part of a +tuple instead. The first element of the tuple returned from `enumerate` is the +index, and the second element is a reference to the element. This is a bit more +convenient than calculating the index ourselves. Because the `enumerate` method returns a tuple, we can use patterns to destructure that tuple. We’ll be discussing patterns more in Chapter 6. In the @@ -1096,9 +989,8 @@ because it’s a separate value from the `String`, there’s no guarantee that i will still be valid in the future. Consider the program in Listing 4-8 that uses the `first_word` function from Listing 4-7. -Filename: src/main.rs - ``` +// src/main.rs fn main() { let mut s = String::from("hello world"); @@ -1130,8 +1022,8 @@ fn second_word(s: &String) -> (usize, usize) { Now we’re tracking a starting *and* an ending index, and we have even more values that were calculated from data in a particular state but aren’t tied to -that state at all. We have three unrelated variables floating around that -need to be kept in sync. +that state at all. We have three unrelated variables floating around that need +to be kept in sync. Luckily, Rust has a solution to this problem: string slices. @@ -1140,10 +1032,10 @@ Luckily, Rust has a solution to this problem: string slices. A *string slice* is a reference to part of a `String`, and it looks like this: ``` - let s = String::from("hello world"); +let s = String::from("hello world"); - let hello = &s[0..5]; - let world = &s[6..11]; +let hello = &s[0..5]; +let world = &s[6..11]; ``` Rather than a reference to the entire `String`, `hello` is a reference to a @@ -1152,17 +1044,15 @@ using a range within brackets by specifying `[starting_index..ending_index]`, where `starting_index` is the first position in the slice and `ending_index` is one more than the last position in the slice. Internally, the slice data structure stores the starting position and the length of the slice, which -corresponds to `ending_index` minus `starting_index`. So in the case of `let +corresponds to `ending_index` minus `starting_index`. So, in the case of `let world = &s[6..11];`, `world` would be a slice that contains a pointer to the -byte at index 6 of `s` with a length value of 5. +byte at index 6 of `s` with a length value of `5`. Figure 4-6 shows this in a diagram. -<img alt="world containing a pointer to the byte at index 6 of String s and a length 5" src="img/trpl04-06.svg" class="center" style="width: 50%;" /> - Figure 4-6: String slice referring to part of a `String` -With Rust’s `..` range syntax, if you want to start at index zero, you can drop +With Rust’s `..` range syntax, if you want to start at index 0, you can drop the value before the two periods. In other words, these are equal: ``` @@ -1197,11 +1087,11 @@ let slice = &s[..]; ``` > Note: String slice range indices must occur at valid UTF-8 character -> boundaries. If you attempt to create a string slice in the middle of a -> multibyte character, your program will exit with an error. For the purposes -> of introducing string slices, we are assuming ASCII only in this section; a -> more thorough discussion of UTF-8 handling is in the “Storing UTF-8 Encoded -> Text with Strings” section of Chapter 8. +boundaries. If you attempt to create a string slice in the middle of a +multibyte character, your program will exit with an error. For the purposes of +introducing string slices, we are assuming ASCII only in this section; a more +thorough discussion of UTF-8 handling is in “Storing UTF-8 Encoded Text with +Strings” on page XX. With all this information in mind, let’s rewrite `first_word` to return a slice. The type that signifies “string slice” is written as `&str`: @@ -1222,10 +1112,10 @@ fn first_word(s: &String) -> &str { } ``` -We get the index for the end of the word in the same way as we did in Listing -4-7, by looking for the first occurrence of a space. When we find a space, we -return a string slice using the start of the string and the index of the space -as the starting and ending indices. +We get the index for the end of the word the same way we did in Listing 4-7, by +looking for the first occurrence of a space. When we find a space, we return a +string slice using the start of the string and the index of the space as the +starting and ending indices. 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 @@ -1237,7 +1127,7 @@ Returning a slice would also work for a `second_word` function: fn second_word(s: &String) -> &str { ``` -We now have a straightforward API that’s much harder to mess up, because the +We now have a straightforward API that’s much harder to mess up because the compiler will ensure the references into the `String` remain valid. Remember the bug in the program in Listing 4-8, when we got the index to the end of the first word but then cleared the string so our index was invalid? That code was @@ -1257,7 +1147,7 @@ fn main() { s.clear(); // error! - println!("the first word is: {}", word); + println!("the first word is: {word}"); } ``` @@ -1274,8 +1164,8 @@ immutable 18 | s.clear(); // error! | ^^^^^^^^^ mutable borrow occurs here 19 | -20 | println!("the first word is: {}", word); - | ---- immutable borrow later used here +20 | println!("the first word is: {word}"); + | ---- immutable borrow later used here ``` Recall from the borrowing rules that if we have an immutable reference to @@ -1287,7 +1177,7 @@ reference in `clear` and the immutable reference in `word` from existing at the same time, and compilation fails. Not only has Rust made our API easier to use, but it has also eliminated an entire class of errors at compile time! -#### String Literals Are Slices +#### String Literals as Slices Recall that we talked about string literals being stored inside the binary. Now that we know about slices, we can properly understand string literals: @@ -1323,9 +1213,10 @@ the type of the `s` parameter If we have a string slice, we can pass that directly. If we have a `String`, we can pass a slice of the `String` or a reference to the `String`. This flexibility takes advantage of *deref coercions*, a feature we will cover in -the “Implicit Deref Coercions with Functions and Methods” section of Chapter -15. Defining a function to take a string slice instead of a reference to a -`String` makes our API more general and useful without losing any functionality: +“Implicit Deref Coercions with Functions and Methods” on page XX. + +Defining a function to take a string slice instead of a reference to a `String` +makes our API more general and useful without losing any functionality: Filename: src/main.rs @@ -1333,16 +1224,18 @@ Filename: src/main.rs fn main() { let my_string = String::from("hello world"); - // `first_word` works on slices of `String`s, whether partial or whole + // `first_word` works on slices of `String`s, whether partial + // or whole let word = first_word(&my_string[0..6]); let word = first_word(&my_string[..]); - // `first_word` also works on references to `String`s, which are equivalent - // to whole slices of `String`s + // `first_word` also works on references to `String`s, which + // are equivalent to whole slices of `String`s let word = first_word(&my_string); let my_string_literal = "hello world"; - // `first_word` works on slices of string literals, whether partial or whole + // `first_word` works on slices of string literals, + // whether partial or whole let word = first_word(&my_string_literal[0..6]); let word = first_word(&my_string_literal[..]); @@ -1355,14 +1248,14 @@ fn main() { ### Other Slices String slices, as you might imagine, are specific to strings. But there’s a -more general slice type, too. Consider this array: +more general slice type too. Consider this array: ``` let a = [1, 2, 3, 4, 5]; ``` -Just as we might want to refer to a part of a string, we might want to refer -to part of an array. We’d do so like this: +Just as we might want to refer to part of a string, we might want to refer to +part of an array. We’d do so like this: ``` let a = [1, 2, 3, 4, 5]; @@ -1388,3 +1281,4 @@ means 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’ll talk about these concepts further throughout the rest of the book. Let’s move on to Chapter 5 and look at grouping pieces of data together in a `struct`. + |