From 0d32bbef7e9f1472abc5eec5a16e12ffb49cad09 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Tue, 17 Jan 2017 17:59:38 -0500 Subject: [PATCH 01/42] Chapter 15: Smart pointers --- src/ch15-00-smart-pointers.md | 354 ++++++++++++++++++++++++++++++++-- 1 file changed, 341 insertions(+), 13 deletions(-) diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index 632993e01..1b4d6ed1b 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -1,28 +1,356 @@ # Smart Pointers -By smart pointers we mean a reference with more characteristics. +Now that we've learned quite a bit of Rust, we can start digging into some more +complicated things. In this chapter, we'll learn about a design pattern in Rust +called a "smart pointer." This pattern allows you to leverage Rust's ownership +and borrowing features to manage all kinds of resources in a safe way. -Example of something that doesn't work +We'll be covering: -Surprise! Vec and String are technically smart pointers too! +* What smart pointers are +* The `Deref` and `Drop` traits +* `Box`, the simplest smart pointer +* Other common smart pointers in the standard library, like `Rc`. +* A family of smart pointers called "cells", which give you "interior + mutability." -This chapter is not a comprehensive list, but will give some examples of the -ones in the standard library. +Let's dive in! +## What are smart pointers + +So what are smart pointers, anyway? Well, we've learned about references in +Rust. "Pointer" is a generic term for something like a reference, that is, +pointers "point at" something else. References are a kind of pointer that only +borrows data; in many cases, smart pointers *own* the data that they point to. +That is, they have extra capabilities that references don't, hence the "smart" +nickname. + +You've already encounted a few smart pointers in the book, we didn't call them +that by name, though. For example, in a certian sense, `String` and `Vec` +are both smart pointers. They own some memory, and allow you to manipualate it. +Another good example is `File`, which we used for our I/O project in chapter +12: it manages a file handle that the operating system gives us. + +Given that this is a design pattern in Rust, this chapter won't cover every +smart pointer that exists. Many libraries will build their own, as well, and +you may write some for your own code. The ones we cover here will be the most +common ones from the standard library. ## `Box` -Don't use very often in your own code -Heap allocated -Express Ownership of a heap allocated thing +The most straightforward smart pointer is a *box*, more properly written as +`Box`. Boxes allow you to put a single value on the heap. (We talked about +the stack vs. the heap in chapter 4.) Using a box looks like this: -The three situations to use Box +```rust +{ + let b = Box::new(5); -1. Trait objects -2. Recursive data structures -3. Extend the lifetime of something + // other code -How this interacts with the Drop trait +} // b goes out of scope here, and is deallocated +``` + +Just like any value that has ownership, when a box goes out of scope, it will +be dealloacated. + +It turns out that putting a single value on the heap isn't very useful, so you +won't use boxes very often. When do you need a box? When you want to ensure +that your type has a known size. What does that mean? Consider this struct: + +```rust,ignore +enum List { + Cons(T, List), + Nil, +} +``` + +This is a 'cons list', that is, a list where each item in the list contains the +next item, until the end, which is called `Nil`. Using one would look like this: + +```rust,ignore +use List::{Cons, Nil}; + +let list = Cons(1, Cons(2, Cons(3, Nil))); +``` + +But if we try to compile the above code, we get an error: + +```text +error[E0072]: recursive type `main::List` has infinite size + --> :3:1 + | +3 | enum List { + | ^ recursive type has infinite size + | + = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to + make `main::List` representable +``` + +The type 'has infinite size'. Why is that? Well, `List` is generic. We +can create a `List` of integers, of strings, of, well, anything. But +different types can take up different amounts of memory. So when the Rust +compiler looks at a type like this: + +```rust +enum SomeEnum { + A(T), + B, +} +``` + +It says "How much memory do I need to allocate for a value of `SomeEnum`? +Let's look at `A`. Well, it has a value of type `T`, so we can use however much +memory `T` needs. Then, let's look at `B`. It doesn't save a value, so we don't +need any extra memory. Done." But consider a *recursive* type, like this: + +```rust,ignore +enum SomeEnum { + A(SomeEnum), + B, +} +``` + +Now the compiler will say, "How much memory do I need to allocate for a value +of `SomeEnum`? Let's look at `A`. Well, it has a value of type `SomeEnum`, +so we need to figure out how much memory a `SomeEnum` needs. Let's look at +`A`. Well, it has a value of type `SomeEnum`, so we need to figure out how +much memory a `SomeEnum` needs. Let's look at `A`. Well, it has a value of +type `SomeEnum`, so we need to figure out how much memory a `SomeEnum` +needs. Let's look at..." into infinity. In order to figure out how much memory +`SomeEnum::A` needs, we need to figure out how much memory `SomeEnum::A` needs. +It's impossible to know! + +The compiler has a helpful suggestion in the error output: + +```text += help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to + make `main::List` representable +``` + +Because a `Box` is a pointer, we always know what size it is: a `usize`. +So if we change our definition to look like this: + +```rust,ignore +enum SomeEnum { + A(Box>), + B, +} +``` + +The compiler will look at this type, and say "How much memory do I need to +allocate for a value of `SomeEnum`? Let's look at `A`. Well, it has a value of +type `Box>`, and we know that a box always has the size of a +`usize`. Then, let's look at `B`. It doesn't save a value, so we don't need any +extra memory. Done." We've broken the infinite, recursive chain by adding in a +box. This is the main area where boxes are useful: breaking up an infinite data +structure so that the compiler can know what size it is. We'll look at a second +variant of this problem in chapter 17, with 'trait objects'. + +Even though you won't be using boxes very often, they are a good way to +understand the smart pointer pattern. What makes boxes smart pointers? Largely, +it's through implementing two important traits: `Deref` and `Drop`. Let's +investigate how boxes use these in more detail. + +## The `Deref` trait + +The first important trait is `Deref`. It allows us to override the `*` +operator. Remember it from when we talked about references? It looks like this: + +```rust +let mut x = 5; +{ + let y = &mut x; + + *y += 1 +} + +assert_eq!(6, x); +``` + +We use `*y` to access the thing that `y` refers to, rather than `y` itself. +Here's an example of overloading `*` using `Deref`: + +```rust +use std::ops::Deref; + +struct DerefExample { + value: T, +} + +impl Deref for DerefExample { + type Target = T; + + fn deref(&self) -> &T { + &self.value + } +} + +fn main() { + let example = DerefExample { value: 'a' }; + + assert_eq!('a', *example); +} +``` + +Most of this should look familliar: a struct, a trait, a main function. There +is one tricky bit: like we said in chapter 13 on Iterators, the `type Target = +T;` syntax is "associated types", which is covered in Chapter 20. Don't worry +about it too much, it is a slightly different way of delcaring a generic +parameter. + +if you look at the `assert_eq!`, we're comparing `'a'` to `*example`: the `*` +is what calls `Deref::deref`. And in the implementation, we can see that we +return a reference to our `value` field, so that's the result we get. Easy! + +### `Deref` coercions. + +There's one other trick with `Deref`: it's one place where Rust will do +automatic coercions. Consider this code: + +```rust +fn takes_a_string_slice(s: &str) { + println!("got: {}", s); +} + +let hello = String::from("hello"); + +takes_a_string_slice(&hello); +``` + +This code _shouldn't_ work, but it does. `takes_a_string_slice`, well, takes a +string slice, a `&str`, as an argument. We pass it `&hello`, which, given that +`hello` is a `String`, should be a `&String`. What gives? + +It turns out that `String`s implement `Deref`, and when they do, they return +string slices! This means that `&String` will automatically coerce to a slice +of the full string. + +There's also a `DerefMut` trait for overriding `*` on `&mut T`s in the same +fashion that we use `Deref` to override `*` on `&T`s. + +Rust does this kind of coercion in three cases: + +* From `&T` to `&U` when `T: Deref`. +* From `&mut T` to `&mut U` when `T: DerefMut`. +* From `&mut T` to `&U` when `T: Deref`. + +The first two are the same, except for mutability: if you have a `&T`, and +`T` implements `Deref` to some type `U`, you can get a `&U` transparently. Same +for mutable references. The last one is more tricky: if you have a mutable +reference, it will also coerece to an immutable one. The other case is _not_ +possible though: immutable references will never coerece to mutable ones. + +## The `Drop` trait + +Next up: `Drop`. `Drop` lets us run some code when something is about to go out +of scope. It looks like this: + +```rust +struct Fireworks { + number: i32, +} + +// Drop is in the prelude, so we don't need to import it +impl Drop for Fireworks { + fn drop(&mut self) { + println!("BOOM! {} fireworks explode!", self.number); + } +} + +fn main() { + let f = Fireworks { number: 10 }; + println!("Fireworks created."); + println!("Wait for it..."); +} +``` + +When we run this program, we'll see + +```text +Fireworks created. +Wait for it... +BOOM! 10 fireworks explode! +``` + +printed to the screen. Our message is printed, and then when `f` goes out of +scope at the end of `main`, `drop` is called, and we see the message about +exploding printed. We can also use the `drop` function to call `Drop` a bit +earlier: + +```rust,ignore +fn main() { + let f = Fireworks { number: 10 }; + println!("Fireworks created."); + drop(f); + println!("Wait for it..."); +} +``` + +This will print: + +```text +Fireworks created. +BOOM! 10 fireworks explode! +Wait for it... +``` + +Normally, you wouldn't want to wait for fireworks _after_ they explode, but you +get the idea. + +The ability to run some code when something goes out of scope is very powerful. +For example, here's something that looks similar to a box. This code won't +_work_, but it illustrates the concept: + +```rust,ignore +struct MyBox { + data: &T, +} + +impl MyBox { + fn new(data: T) { + // allocate some memory + let mut memory = allocate_memory(); + + // copy the data into that memory + *memory = T; + + // return a box containing the reference to the memory + MyBox { + data: memory, + } + } +} + +impl Drop for MyBox { + fn drop(&mut self) { + free_memory(self.data); + } +} +``` + +So first, we declare `MyBox` to have a reference to some data. We can't use +actual `&T` references for this, we'd use `*const T`, but we won't talk about +*raw pointer*s until Chapter 20. So for now, pretend that this works; it's the +same idea. + +In `new`, we allocate some memory by asking the operating system for it. This +function doesn't exist in Rust today, so we made up a function name, +`allocate_memory`, for it. This function would return a reference to the new +memory we've been granted. We then copy our data into it by using the `*` +operator. So after the assignment, `memory` will be pointing to a copy of our +`data`. Finally, we return our new `MyBox`, created from this memory. + +That takes care of allocation, but what about deallocation? For that, we use +`Drop`, along with another fake function: `free_memory`. This function will +return the memory back to the operating system. + +So we're automatically allocating memory in `new`, and then automatically +freeing it in `drop`. We can't mess it up. The ownership system makes sure that +we call `drop` at the right time, and things work out. + +Now that you understand the basics of smart pointers, let's talk about a few +other useful ones in the standard library. ## `Rc` From 4ad2690f708fc8ec36dfd43a754cdf16209ff649 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Tue, 14 Feb 2017 18:49:51 -0500 Subject: [PATCH 02/42] more work on smart pointers --- src/ch15-00-smart-pointers.md | 193 ++++++++++++++++++++++++++-------- 1 file changed, 152 insertions(+), 41 deletions(-) diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index 1b4d6ed1b..a45297ba4 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -354,74 +354,150 @@ other useful ones in the standard library. ## `Rc` -Reference counted. Rc is for *multiple ownership* - this thing should get -deallocated when all of the owners go out of scope. +In the majority of cases, ownership is very clear: you know exactly which +binding owns a given bit of data. However, this isn't always the case; +sometimes, you may actually need multiple owners. For this, Rust has a type +called `Rc`. Its name is an abbreviation for 'reference counting'. -Show the data structure: +Let's look at an example: ```rust -struct Rc { - data: Box, - strong_reference_count: usize, - weak_reference_count: usize, -} +use std::rc::Rc; + +let r1 = Rc::new(5); +let r2 = r1.clone(); ``` -Talk through this. +You've seen the `clone` method previously, it's usually used for making a +complete copy of some data. With `Rc`, though, it doesn't make a full copy. +`Rc` holds a 'reference count', that is, a count of how many clones exist. +Let's look at this example in more detail: -This only works if the data is immutable. +```rust +use std::rc::Rc; -What happens when you clone an Rc: data isn't cloned, increase the strong count. -When an Rc clone goes out of scope, the count goes down. +let r1 = Rc::new(5); // here, we have an Rc with a reference count of one. -### Rc Cycles +let r2 = r1.clone(); // here, we increment the reference count; now both r1 and + // r2 both refer to the same 5; and we have a total count + // of two. -This is how you leak memory in rust, which btw is totally safe. +// Here, the scope is ending. r2 goes out of scope first. When it does, it +// doesn't free the 5, like a Box would; it decrements the count. So after +// r2 goes out of scope, the count is one. -Is this garbage collecting? Well it's not tracing GC... if you use Rc and had -a cycle detector, it would be functionally equivalent to a tracing GC. Different -runtime characteristics tho. +// Now, r1 goes out of scope. When it does, it decrements the count. The count +// is now zero. Since the count is zero, the value is deallocated. +``` +This is the basic strategy: you make an `Rc` with `new`, and then call +`clone` for all of the other owners you need. When each `Rc` goes out of +scope, they decrease the count, and when the count is zero, the value is +deallocated. This strategy lets us have multiple owners, as the count will +ensure that the value remains valid as long as any of the owners still exists. -#### Solution: turn an Rc into a `Weak` - -Same as Rc, but doesn't count towards the strong ref count. When you do this, the -strong ref count goes down and the weak count goes up. - -Data gets cleaned up when the strong count is 0, no matter what the weak count is. -However, Rc structure is kept until weak reference count also goes to zero, so weak pointers do not become dangling pointers. -At this point, attempt to upgrade Weak pointer will result into None. -Only when weak reference counter also reduces to zero, Rc structure is freed. +This idea is simple enough, but there are a few twists! Here's the first: In +order for this to be okay, the data inside of an `Rc` must be immutable. If +it were mutable, we'd run into a similar problem with borrowing: two mutable +borrows to the same place can cause a lot of problems. There's another twist, +too: an "`Rc` cycle." While single ownership is easy to reason about, +multiple owenership is a lot trickier. Before we cover these situations in +detail, we need to talk about another type: `RefCell`. ## `RefCell` -Single owner of mutable data +Unlike `Rc`, the `RefCell` type represents single ownership over the +data that it holds. So, what makes `RefCell` different than a type like +`Box`? For that, we'll have to recall the borrowing rules we learned in +Chapter 4: -The ownership rules checked at runtime instead of compile time. +1. At any given time, you can have either but not both of: + * One mutable reference. + * Any number of immutable references. +2. References must always be valid. -Only single threaded. See next chapter. +With references, these invariants are enforced at compile time. But with +`RefCell`, these invariants are enforced *at runtime*. With references, +if you break these rules, you'll get a compiler error. With `RefCell`, +if you break these rules, you'll get a `panic!`. -### `borrow` and `borrow_mut` methods +Before we talk about how to use `RefCell`, we should mention one more thing: +`RefCell` is only useful in single-threaded scenarios; it's not threadsafe. +We'll talk about concurrency and paralellism in the next chapter; for now, all +you need to know is that if you try to use `RefCell` in a single-threaded +context, you'll get a compile time error. -Checks all the rules and panics at runtime if the code violates them. +### The `borrow` and `borrow_mut` methods -1. The borrow checker is conservative and people can know more things. (no you -don't, but if you really want to go back to debugging segfaults, feel free) +With references, we use the `&` and `&mut` syntax to create references and +mutable references, respectively. But with `RefCell`, we use the `borrow` +and `borrow_mut` methods: -2. For when you're only allowed to have an immutable thing (which could be `Rc`) -but you need to be able to mutate the underlying data. +```rust +use std::cell::RefCell; + +let five = RefCell::new(5); + +// we need these scopes so we don't break the rules! +{ + let r1 = five.borrow(); + let r2 = five.borrow(); + let r3 = five.borrow(); + + // r1, r2, and r3 are all immutable references. +} + +{ + let r = five.borrow_mut(); + + // r1 is a mutable reference +} +``` + +If we call both `borrow` and `borrow_mut` in the same scope, we'll get a panic. + +So why do we need `RefCell`? What good is it to enforce the rules at runtime, +instead of compile time? + +Static analysis, like Rust performs, is inherently conservative. That is, if we +accept an incorrect program, very bad things happen, but if we reject a correct +program, the programmer will be inconvenienced, but nothing catastrophic can +occur. `RefCell` is useful in two situations: + +1. When you know that the borrowing rules are respected, but when the compiler +can't understand that that's true. +2. When you need "interior mutability." + +We'll cover "interior mutability" later in this chapter, but first, let's talk +about a different kind of cell: `Cell`. ## `Cell` -Same thing as RefCell but for types that are Copy. No borrow checking rules here -anyway. So just reason #2 above. +`Cell` is the same as `RefCell`, but only for types that are `Copy`. Instead +of `borrow` and `borrow_mut` methods, it has `get` and `set` methods: -## Is this really safe? Yes! +```rust +use std::cell::Cell; -RefCell is still doing the checks, just at runtime -Cell is safe bc Copy types don't need the ownership rules anyway +let mut five = Cell::new(5); -### The Interior Mutability Pattern +five.set(6); // not five any more O_O + +println!("five is: {}", five.get()); +``` + +The difference between `Cell` and `RefCell` mirrors the difference +between types that are `Copy` and types that are not; if we don't need the +ownership rules, then we can do things in a much simpler way. If we do, then we +need to deal with borrowing, rather than just copying data around. + +So when should you use `Cell`? Since we don't have the borrowing element, +the advice is the same as for `RefCell`, but only the second rule: use +`Cell` when you need interior mutability. + +But what is 'interior mutability' anyway? + +## The Interior Mutability Pattern The Interior Mutability Pattern is super unsafe internally but safe to use from the outside and is totally safe, totally, trust us, seriously, it's safe. @@ -432,6 +508,41 @@ UnsafeCell turns off those optimizations so that everything doesn't break. This is how you can opt-out of the default of Rust's ownership rules and opt in to different guarantees. +### Cycles + +We've shown that with `Rc`s, when the last one goes out of scope, the value +is deallocated. But what about this program? + +```rust +use std::rc::Rc; + +struct Cycle { + really_bad: Option>, + leaked_data: i32, +} + +fn main() { + let mut oh_no = Rc::new(Cycle { + really_bad: None, + leaked_data: 5, + }); + + let clone = oh_no.clone(); + + oh_no.really_bad = Some(clone); +} +``` + +#### Solution: turn an Rc into a `Weak` + +Same as Rc, but doesn't count towards the strong ref count. When you do this, the +strong ref count goes down and the weak count goes up. + +Data gets cleaned up when the strong count is 0, no matter what the weak count is. + +Why is the weak count needed then???? + + ## Summary If you want to implement your own smart pointer, go read the Nomicon. From ac61cbdd7a557b1b4669f4a3ddf604ef33ea5ce3 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Wed, 22 Feb 2017 14:54:02 -0500 Subject: [PATCH 03/42] finish off draft --- src/ch15-00-smart-pointers.md | 138 +++++++++++++++++++++++++++++----- 1 file changed, 120 insertions(+), 18 deletions(-) diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index a45297ba4..5bba93bf8 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -479,7 +479,7 @@ of `borrow` and `borrow_mut` methods, it has `get` and `set` methods: ```rust use std::cell::Cell; -let mut five = Cell::new(5); +let five = Cell::new(5); five.set(6); // not five any more O_O @@ -499,14 +499,61 @@ But what is 'interior mutability' anyway? ## The Interior Mutability Pattern -The Interior Mutability Pattern is super unsafe internally but safe to use -from the outside and is totally safe, totally, trust us, seriously, it's safe. +*Interior mutability* is a design pattern in Rust for allowing you to mutate +something that's immutable. Wait, what? Let's compare these two pieces of code. +What's different about them? -Allude to `UnsafeCell` maybe. Affects optimizations since &mut T is unique. -UnsafeCell turns off those optimizations so that everything doesn't break. +```rust +use std::cell::Cell; -This is how you can opt-out of the default of Rust's ownership rules and opt -in to different guarantees. +// one +let mut five = 5; + +five = 6; + +// two +let five = Cell::new(5); + +five.set(6); +``` + +There are three things that are different: + +1. We use `5` in sample one, but `Cell::new(5)` in sample two. +2. We use `=` in sample one, but `set` in sample two. +3. `five` is mutable in sample one, but not in sample two. + +That third difference? That's interior mutability. + +Why are we allowed to do this? Well, to some degree, we're not. The reason we +call interior mutability a "pattern" is that it's not really a language +feature, it's a design pattern for libraries. More specifically, it's a pattern +that uses `unsafe` code inside to bend Rust's usual rules. We haven't yet covered +unsafe code in-depth, we will in Chapter 20. Luckily for us, you don't have to +understand how it works inside to use it. All you need to know is that the +various family of `Cell` types, as well as some others like `Mutex` (that we'll +cover in the next chapter, on concurrency) follow this pattern. + +Why is this useful? Well, remember when we said that `Rc` has to store +immutable data? Given that `RefCell` is immutable, but has interior mutability, +we can combine `Rc` and `RefCell` to get a type that's both reference +counted and mutable. Like this: + +```rust +use std::rc::Rc; +use std::cell::RefCell; + +let five = Rc::new(RefCell::new(5)); + +let other_rc = five.clone(); + +*other_rc.borrow_mut() = 6; +``` + +This is where interior mutability is useful: when you have something that +requires immutability, but you also need to mutate something. This comes up +with types like `Rc`, but it can also come up in concurrency situations. In +general, it's a fairly rare thing to need, but when you need it, it does exist. ### Cycles @@ -515,37 +562,92 @@ is deallocated. But what about this program? ```rust use std::rc::Rc; +use std::cell::RefCell; struct Cycle { - really_bad: Option>, + really_bad: RefCell>>, leaked_data: i32, } fn main() { let mut oh_no = Rc::new(Cycle { - really_bad: None, + really_bad: RefCell::new(None), leaked_data: 5, }); - let clone = oh_no.clone(); + let clone = oh_no.clone(); - oh_no.really_bad = Some(clone); + *oh_no.really_bad.borrow_mut() = Some(clone); } ``` +There's a lot going on here. Fundamentally, `Cycle` is a type that contains an +`Rc`. This means that we can have a 'referene cycle', hence the name of +the struct. Here, we've constructed one in `main`: we have `oh_no`, and then we +create a clone of it, `clone`. Since we've made a clone of it, the reference +count is two: one for the initial `Rc`, and one for the clone. When `oh_no` +goes out of scope at the end of `main`, it will decrement the count to one. But +that's it: `clone` never really goes out of scope, since it was moved into +`oh_no`. This means that this memory is now unreachable, yet will never be +cleaned up. It'll just sit there with a count of one, forever. In this +specific case, the program ends right away, so it's not a problem, but in a +more complex program, it would be. + +Now, as you can see, doing this is very hard. To be honest, your authors had to +look up previous discussions of an example to get this right. But it can +happen, and the way that it happens is reasonably obvious: If you have an +`Rc` that contains an `Rc`, beware. + #### Solution: turn an Rc into a `Weak` -Same as Rc, but doesn't count towards the strong ref count. When you do this, the -strong ref count goes down and the weak count goes up. +To help with this problem, the Rust standard library contains a different +type: `Weak`. Let's see what that looks like: -Data gets cleaned up when the strong count is 0, no matter what the weak count is. +```rust +use std::rc::{Rc, Weak}; +use std::cell::RefCell; -Why is the weak count needed then???? +struct Cycle { + really_bad: RefCell>>, + leaked_data: i32, +} + +fn main() { + let mut oh_no = Rc::new(Cycle { + really_bad: RefCell::new(None), + leaked_data: 5, + }); + + let clone = Rc::downgrade(&oh_no.clone()); + + *oh_no.really_bad.borrow_mut() = Some(clone); +} +``` + +`Weak` is exactly like `Rc`, except that its reference count doesn't, well, +count when determining if something should be freed. You can turn an `Rc` into +a `Weak` with the `Rc::downgrade` associated method, which takes an `&Rc` +as an argument, and gives a `Weak` back. + +So in this example, when we call `oh_no.clone()`, we increment the count to two. +But when we pass that clone to `downgrade`, that count goes down again, to one. +Now, at the end of the function, when `oh_no` goes out of scope, it reduces the +count from one to zero, and the memory is freed. Success! We've broken the cycle. + +If you're doing complex things with `Rc`s, you should investigate if you +have a cycle, and insert a `Weak` so that your memory doesn't leak. The +specifics depend on exactly what you're doing, but luckily, this isn't a +Rust-specific idea; all of this translates over to other reference counting +libraries in other languages, so doing some reading about it should help you. ## Summary -If you want to implement your own smart pointer, go read the Nomicon. +Whew! Smart pointers are powerful, but complex. We've covered the basics of +smart pointers, and how to use some of the most common smart pointers. +Implementing your own smart pointers is out of the scope of this book; you +should check out the Nomicon if you're interested in building these kinds of +abstractions. -Now let's talk about concurrency, and some smart pointers that can be used -with multiple threads. +Next, let's talk about concurrency in Rust. We'll even learn aobut a few new +smart pointers that can help us with it. From 01e407ac757282c6276fc1664d68196aadd59a84 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 23 Feb 2017 13:11:44 -0500 Subject: [PATCH 04/42] First editing pass --- src/ch15-00-smart-pointers.md | 672 ++++++++++++++++++++-------------- 1 file changed, 404 insertions(+), 268 deletions(-) diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index 5bba93bf8..8b8ea1156 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -1,62 +1,90 @@ # Smart Pointers Now that we've learned quite a bit of Rust, we can start digging into some more -complicated things. In this chapter, we'll learn about a design pattern in Rust -called a "smart pointer." This pattern allows you to leverage Rust's ownership -and borrowing features to manage all kinds of resources in a safe way. +complicated concepts. In this chapter, we'll learn about a design pattern in +Rust called a *smart pointer*. This pattern allows us to leverage Rust's +ownership and borrowing features to manage all kinds of resources in a safe way. + +TODO: more motivation We'll be covering: * What smart pointers are * The `Deref` and `Drop` traits * `Box`, the simplest smart pointer -* Other common smart pointers in the standard library, like `Rc`. -* A family of smart pointers called "cells", which give you "interior - mutability." +* Other common smart pointers in the standard library, like `Rc` +* A family of smart pointers called *cells* which give you *interior + mutability* Let's dive in! -## What are smart pointers +## Smart Pointers Own and Manage Data or Resources So what are smart pointers, anyway? Well, we've learned about references in -Rust. "Pointer" is a generic term for something like a reference, that is, -pointers "point at" something else. References are a kind of pointer that only -borrows data; in many cases, smart pointers *own* the data that they point to. -That is, they have extra capabilities that references don't, hence the "smart" -nickname. +Rust in Chapter 4. *Pointer* is a generic programming term for something like a +reference, that is, pointers "point at" data somewhere else. References are a +kind of pointer that only borrow data; by contrast, in many cases, smart +pointers *own* the data that they point to. That is, they have extra +capabilities that references don't, hence the "smart" nickname. -You've already encounted a few smart pointers in the book, we didn't call them -that by name, though. For example, in a certian sense, `String` and `Vec` -are both smart pointers. They own some memory, and allow you to manipualate it. -Another good example is `File`, which we used for our I/O project in chapter -12: it manages a file handle that the operating system gives us. +We've actually already encounted a few smart pointers in this book, we didn't +call them that by name, though. For example, in a certian sense, `String` and +`Vec` from Chapter 8 are both smart pointers. They own some memory and allow +you to manipualate it. Another good example is `File`, which we used for our +I/O project in Chapter 12: it owns and manages a file handle that the operating +system gives us. -Given that this is a design pattern in Rust, this chapter won't cover every -smart pointer that exists. Many libraries will build their own, as well, and -you may write some for your own code. The ones we cover here will be the most -common ones from the standard library. +Given that this is a general design pattern in Rust, this chapter won't cover +every smart pointer that exists. Many libraries will build their own as well, +and you may write some for your own code. The ones we cover here will be the +most common ones from the standard library. -## `Box` +## `Box` Points to Data on the Heap and Has a Known Size -The most straightforward smart pointer is a *box*, more properly written as -`Box`. Boxes allow you to put a single value on the heap. (We talked about -the stack vs. the heap in chapter 4.) Using a box looks like this: +The most straightforward smart pointer is a *box*, whose type is more properly +written as `Box`. Boxes allow you to put a single value on the heap, and the +pointer to that value lives on the stack. (We talked about the stack vs. the +heap in Chapter 4.) Listing 15-1 shows how to use a box to store an `i32` on +the heap: + +
+Filename: src/main.rs ```rust -{ +fn main() { let b = Box::new(5); - // other code + println!("b = {}", b); -} // b goes out of scope here, and is deallocated +} // b goes out of scope here, and the data on the heap is deallocated ``` -Just like any value that has ownership, when a box goes out of scope, it will -be dealloacated. +
-It turns out that putting a single value on the heap isn't very useful, so you -won't use boxes very often. When do you need a box? When you want to ensure -that your type has a known size. What does that mean? Consider this struct: +Listing 15-1: Storing an `i32` value on the heap using a box + +
+
+ +This will print `b = 5`. In this case, we can access the data in the box in a +similar way as we would if this data was on the stack. Just like any value that +has ownership, when a box goes out of scope, it will be dealloacated, which +means the box (stored on the stack) and the data (stored on the heap) will both +be deallocated. + +Putting a single value on the heap isn't very useful, so you won't use boxes in +the way that Listing 15-1 does very often. A time when boxes are useful are +when you want to ensure that your type has a known size. For example, consider +Listing 15-2, which contains an enum definition for a *cons list*, a type of +data structure that comes from functional programming. A cons list is a list +where each item contains the next item until the end of the list, which is +signified by a value called `Nil`. Note that we aren't introducing the idea of +"nil" or "null" that we discussed in Chapter 6, this is just a regular enum +variant name we're using because it's the canonical name to use when describing +this data structure. + +
+Filename: src/main.rs ```rust,ignore enum List { @@ -65,166 +93,258 @@ enum List { } ``` -This is a 'cons list', that is, a list where each item in the list contains the -next item, until the end, which is called `Nil`. Using one would look like this: +
+ +Listing 15-2: An enum definition for a cons list data structure + +
+
+ +Using a cons list to store the list `1, 2, 3` would look like this: ```rust,ignore use List::{Cons, Nil}; -let list = Cons(1, Cons(2, Cons(3, Nil))); +fn main() { + let list = Cons(1, Cons(2, Cons(3, Nil))); +} ``` -But if we try to compile the above code, we get an error: +The first `Cons` value holds `1` and another `List` value. This `List` +value is another `Cons` value that holds `2` and another `List` value. This +is one more `Cons` value that holds `3` and a `List` value, which is finally +`Nil`, the non-recursive variant that signals the end of the list. + +However, if we try to compile the above code, we get the error shown in Listing +15-3: + +
```text -error[E0072]: recursive type `main::List` has infinite size - --> :3:1 +error[E0072]: recursive type `List` has infinite size + --> src/main.rs:1:1 | -3 | enum List { - | ^ recursive type has infinite size +1 | enum List { + | _^ starting here... +2 | | Cons(T, List), +3 | | Nil, +4 | | } + | |_^ ...ending here: recursive type has infinite size | = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to - make `main::List` representable + make `List` representable ``` -The type 'has infinite size'. Why is that? Well, `List` is generic. We -can create a `List` of integers, of strings, of, well, anything. But -different types can take up different amounts of memory. So when the Rust -compiler looks at a type like this: +
+ +Listing 15-3: The error we get when attempting to define a recursive enum + +
+
+ +The error says this type 'has infinite size'. Why is that? It's because we've +defined `List` to have a variant that is recursive: it holds another value +of itself. This means Rust can't figure out how much space it needs in order to +store a `List` value. Let's break this down a bit: recall the `Message` enum +we defined in Listing 6-2 when we discussed enum definitions in Chapter 6: ```rust -enum SomeEnum { - A(T), - B, +enum Message { + Quit, + Move { x: i32, y: i32 }, + Write(String), + ChangeColor(i32, i32, i32), } ``` -It says "How much memory do I need to allocate for a value of `SomeEnum`? -Let's look at `A`. Well, it has a value of type `T`, so we can use however much -memory `T` needs. Then, let's look at `B`. It doesn't save a value, so we don't -need any extra memory. Done." But consider a *recursive* type, like this: +When Rust needs to know how much space to allocate for a `Message` value, it +can go through each of the variants and see that `Message::Quit` does not need +any space, `Message::Move` needs enough space to store two `i32` values, and so +forth. Therefore, the most space a `Message` value will need is the space it +would take to store the largest of its variants. -```rust,ignore -enum SomeEnum { - A(SomeEnum), - B, -} -``` +When the Rust compiler looks at a type like the enum in Listing 15-2, it tries +to figure out how much memory is needed to store value of `List`, and starts +by looking at the `Cons` variant. The `Cons` variant holds a value of type `T` +and a value of type `List`, so it can use however much the size of `T` is +plus the size of `List`. To figure out how much memory a `List` needs, it +looks at its variants, starting with the `Cons` variant. The `Cons` variant +holds a value of type `T` and a value of type `List`, and this continues +infinitely. Rust can't figure out how much space to allocate for recursively +defined types, so the compiler gives the error in Listing 15-3. -Now the compiler will say, "How much memory do I need to allocate for a value -of `SomeEnum`? Let's look at `A`. Well, it has a value of type `SomeEnum`, -so we need to figure out how much memory a `SomeEnum` needs. Let's look at -`A`. Well, it has a value of type `SomeEnum`, so we need to figure out how -much memory a `SomeEnum` needs. Let's look at `A`. Well, it has a value of -type `SomeEnum`, so we need to figure out how much memory a `SomeEnum` -needs. Let's look at..." into infinity. In order to figure out how much memory -`SomeEnum::A` needs, we need to figure out how much memory `SomeEnum::A` needs. -It's impossible to know! - -The compiler has a helpful suggestion in the error output: +The compiler did give a helpful suggestion in the error output: ```text = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to - make `main::List` representable + make `List` representable ``` -Because a `Box` is a pointer, we always know what size it is: a `usize`. -So if we change our definition to look like this: +Because a `Box` is a pointer, we always know what size it is: a `usize`, +which is the size of a pointer. So if we change our definition from Listing +15-2 to look like this: ```rust,ignore -enum SomeEnum { - A(Box>), - B, +enum List { + Cons(T, Box>), + Nil, } ``` -The compiler will look at this type, and say "How much memory do I need to -allocate for a value of `SomeEnum`? Let's look at `A`. Well, it has a value of -type `Box>`, and we know that a box always has the size of a -`usize`. Then, let's look at `B`. It doesn't save a value, so we don't need any -extra memory. Done." We've broken the infinite, recursive chain by adding in a -box. This is the main area where boxes are useful: breaking up an infinite data -structure so that the compiler can know what size it is. We'll look at a second -variant of this problem in chapter 17, with 'trait objects'. +The compiler will be able to figure out the size of a `List` value. It will +look at this type, and start by looking at the `Cons` variant. The `Cons` +variant will need the size of whatever `T` is, plus the space to store a +`usize`, since a box always has the size of a `usize`. Then it looks at the +`Nil` variant, which does not store a value, so it doesn't need any extra +memory. We've broken the infinite, recursive chain by adding in a box. This is +the main area where boxes are useful: breaking up an infinite data structure so +that the compiler can know what size it is. We'll look at another case where +Rust has data of unknown size in Chapter 17 when we discuss trait objects. Even though you won't be using boxes very often, they are a good way to -understand the smart pointer pattern. What makes boxes smart pointers? Largely, -it's through implementing two important traits: `Deref` and `Drop`. Let's -investigate how boxes use these in more detail. +understand the smart pointer pattern. The attribute of the `Box` type that +makes it a smart pointer is that it implements two important traits: `Deref` +and `Drop`. Let's investigate how boxes use these in more detail. -## The `Deref` trait +## The `Deref` Trait Allows Access to the Data Through a Reference -The first important trait is `Deref`. It allows us to override the `*` -operator. Remember it from when we talked about references? It looks like this: +The first important smart pointer-related trait is `Deref`, which allows us to +override the `*` operator, the dereference operator (as opposed to the +multiplication operator). Overriding `*` for smart pointers makes accessing the +data behind the smart pointer convenient, and we'll talk about what we mean by +convenient in the next section about deref coercions. Remember using `*` when +we talked about references, like this: + +TODO: put this back in ch 4 ```rust let mut x = 5; { let y = &mut x; - + *y += 1 } assert_eq!(6, x); ``` -We use `*y` to access the thing that `y` refers to, rather than `y` itself. -Here's an example of overloading `*` using `Deref`: +We use `*y` to access the data that `y` refers to, rather than `y` itself, +which is a reference. + +Listing 15-4 has an example of overloading `*` using `Deref` on a struct we've +defined to hold mp3 data and metadata. `Mp3` is, in a sense, a smart pointer: +it owns the `Vec` data containing the audio. In addition, it holds some +optional metadata, in this case the artist and title of the song in the audio +data. We want to be able to conveniently access the audio data, not the +metadata, so we implement the `Deref` trait to return the audio data: + +
+Filename: src/main.rs ```rust use std::ops::Deref; -struct DerefExample { - value: T, +struct Mp3 { + audio: Vec, + artist: String, + title: String, } -impl Deref for DerefExample { - type Target = T; +impl Deref for Mp3 { + type Target = Vec; - fn deref(&self) -> &T { - &self.value + fn deref(&self) -> &Vec { + &self.audio } } fn main() { - let example = DerefExample { value: 'a' }; + let my_favorite_song = Mp3 { + // we would read the actual audio data from an mp3 file + audio: vec![1, 2, 3], + artist: String::from("Nirvana"), + title: String::from("Smells Like Teen Spirit"), + }; - assert_eq!('a', *example); + assert_eq!(vec![1, 2, 3], *my_favorite_song); } ``` -Most of this should look familliar: a struct, a trait, a main function. There -is one tricky bit: like we said in chapter 13 on Iterators, the `type Target = -T;` syntax is "associated types", which is covered in Chapter 20. Don't worry -about it too much, it is a slightly different way of delcaring a generic -parameter. +
-if you look at the `assert_eq!`, we're comparing `'a'` to `*example`: the `*` -is what calls `Deref::deref`. And in the implementation, we can see that we -return a reference to our `value` field, so that's the result we get. Easy! +Listing 15-4: An implementation of the `Deref` trait on a struct that holds mp3 +file data and metadata -### `Deref` coercions. +
+
-There's one other trick with `Deref`: it's one place where Rust will do -automatic coercions. Consider this code: +Most of this should look familliar: a struct, a trait implementation, a main +function that creates an instance of the struct. There is one part we haven't +explained thoroughly yet: similarly to Chapter 13 when we looked at the +Iterator trait with the `type Item`, the `type Target = T;` syntax is defining +an associated type, which is covered in more detail in Chapter 20. Don't worry +about that part of the example too much; it is a slightly different way of +delcaring a generic parameter. -```rust -fn takes_a_string_slice(s: &str) { - println!("got: {}", s); +In the `assert_eq!`, we're verifying that `vec![1, 2, 3]` is the result we get +when dereferencing the `Mp3` instance with `*my_favorite_song`, which is what +happens since we implemented the `deref` method to return the audio data. If +we hadn't implemented the `Deref` trait for `Mp3`, Rust wouldn't compile the +code `*my_favorite_song`: we'd get an error saying type `Mp3` cannot be +dereferenced. + +The reason this code works is that what the `*` operator does behind the scenes +is: + +1. Call `Deref::deref(my_favorite_song)` +2. Dereference the result + +The reason that the return type of the `deref` method is still a reference and +why it's necessary to dereference the result of the method is that if the +`deref` method returned just the value, using `*` would always take ownership. + +### Implicit `deref` Coercions with Functions and Methods + +TODO: consistent spelling of `deref` coercion (`Deref` coercion? deref coercion?) + +Rust tends to favor explicitness over implicitness, but one case where this +does not hold true is *`deref` coercions* of arguments to functions and +methods. A `deref` coercion will automatically convert arguments passed to +functions or methods that are references to pointers or smart pointers into +references to the pointer's contents if needed to match the types of the +parameters defined in the signature. This was added to make calling functions +and methods not need as many explicit references and dereferences with `&` and +`*`. + +Using our `Mp3` struct from Listing 15-4, here's the signature of a function to +compress mp3 audio data that takes a slice of `u8`: + +```rust,ignore +fn compress_mp3(audio: &[u8]) -> Vec { + // the actual implementation would go here } - -let hello = String::from("hello"); - -takes_a_string_slice(&hello); ``` -This code _shouldn't_ work, but it does. `takes_a_string_slice`, well, takes a -string slice, a `&str`, as an argument. We pass it `&hello`, which, given that -`hello` is a `String`, should be a `&String`. What gives? +Because of `deref` coercion and our implementation of the `Deref` trait on +`Mp3`, we can call this function with the data in `my_favorite_song` by using +this code: -It turns out that `String`s implement `Deref`, and when they do, they return -string slices! This means that `&String` will automatically coerce to a slice -of the full string. +```rust,ignore +let result = compress_mp3(&my_favorite_song); +``` + +Without `deref` coercsion and our `Deref` implementation, we would have to +write `compress_mp3(my_favorite_song.audio.as_slice())`. Rust knows that `Mp3` +implements the `Deref` trait and returns `&Vec` from the `deref` method. +The standard library also implements the `Deref` trait on `Vec` to return +`&[T]` from the `deref` method. So Rust will implicitly call `Deref::deref` +twice to turn `&Mp3` into `&Vec` and then into `&[T]` to match the +signature of `compress_mp3`. That means we get to do less typing! Rust will +call `Deref::deref` as many times as it needs to in order to get a reference to +match the parameter's type, when the `Deref` trait is defined for the types +involved. + +TODO: is there a runtime cost for this? There's also a `DerefMut` trait for overriding `*` on `&mut T`s in the same fashion that we use `Deref` to override `*` on `&T`s. @@ -241,10 +361,16 @@ for mutable references. The last one is more tricky: if you have a mutable reference, it will also coerece to an immutable one. The other case is _not_ possible though: immutable references will never coerece to mutable ones. +The reason that the `Deref` trait is important to the smart pointer pattern is +that smart pointers can then be treated like regular pointers for places that +expect regular pointers. We don't have to redefine methods and functions to +take smart pointers explicitly, for example. + ## The `Drop` trait -Next up: `Drop`. `Drop` lets us run some code when something is about to go out -of scope. It looks like this: +The other trait that's important to the smart pointer pattern is the `Drop` +trait. `Drop` lets us run some code when a value is about to go out of scope. +Listing 15-5 shows an implementation of ```rust struct Fireworks { @@ -310,7 +436,7 @@ struct MyBox { impl MyBox { fn new(data: T) { // allocate some memory - let mut memory = allocate_memory(); + let mut memory = allocate_memory(); // copy the data into that memory *memory = T; @@ -318,7 +444,7 @@ impl MyBox { // return a box containing the reference to the memory MyBox { data: memory, - } + } } } @@ -329,6 +455,10 @@ impl Drop for MyBox { } ``` +TODO: replace this with closing a socket and just mention that this could be used to implement a custom memory allocator? + + + So first, we declare `MyBox` to have a reference to some data. We can't use actual `&T` references for this, we'd use `*const T`, but we won't talk about *raw pointer*s until Chapter 20. So for now, pretend that this works; it's the @@ -350,15 +480,25 @@ freeing it in `drop`. We can't mess it up. The ownership system makes sure that we call `drop` at the right time, and things work out. Now that you understand the basics of smart pointers, let's talk about a few -other useful ones in the standard library. +others defined in the standard library that add even more useful functionality. -## `Rc` +## The Reference Counted Smart Pointer `Rc` In the majority of cases, ownership is very clear: you know exactly which -binding owns a given bit of data. However, this isn't always the case; +binding owns a given value. However, this isn't always the case; sometimes, you may actually need multiple owners. For this, Rust has a type called `Rc`. Its name is an abbreviation for 'reference counting'. +This should be used when we wish to dynamically allocate and share some data +(read-only) between various portions of your program, where it is not certain +which portion will finish using the pointer last. It's a viable alternative to +&T when &T is either impossible to statically check for correctness, or creates +extremely unergonomic code where the programmer does not wish to spend the +development cost of working with. + +TODO: insert something like the turtle example +TODO: insert why reference counting is useful-- multiple owners may use the same data, and the data goes out of scope once all of its owners go out of scope and not before. + Let's look at an example: ```rust @@ -376,16 +516,18 @@ Let's look at this example in more detail: ```rust use std::rc::Rc; -let r1 = Rc::new(5); // here, we have an Rc with a reference count of one. - -let r2 = r1.clone(); // here, we increment the reference count; now both r1 and - // r2 both refer to the same 5; and we have a total count - // of two. - -// Here, the scope is ending. r2 goes out of scope first. When it does, it -// doesn't free the 5, like a Box would; it decrements the count. So after -// r2 goes out of scope, the count is one. +fn main() { + let r1 = Rc::new(5); // here, we have an Rc with a reference count of one. + { + let r2 = r1.clone(); // here, we increment the reference count; now both r1 and + // r2 both refer to the same 5; and we have a total count + // of two. + } + // Here, the scope is ending. r2 goes out of scope first. When it does, it + // doesn't free the 5, like a Box would; it decrements the count. So after + // r2 goes out of scope, the count is one. +} // Now, r1 goes out of scope. When it does, it decrements the count. The count // is now zero. Since the count is zero, the value is deallocated. ``` @@ -394,109 +536,20 @@ This is the basic strategy: you make an `Rc` with `new`, and then call `clone` for all of the other owners you need. When each `Rc` goes out of scope, they decrease the count, and when the count is zero, the value is deallocated. This strategy lets us have multiple owners, as the count will -ensure that the value remains valid as long as any of the owners still exists. +ensure that the value remains valid as long as any of the owners still exist. This idea is simple enough, but there are a few twists! Here's the first: In order for this to be okay, the data inside of an `Rc` must be immutable. If it were mutable, we'd run into a similar problem with borrowing: two mutable -borrows to the same place can cause a lot of problems. There's another twist, +borrows to the same place can cause a lot of problems. + +TODO: stop here, move this later? + +There's another twist, too: an "`Rc` cycle." While single ownership is easy to reason about, multiple owenership is a lot trickier. Before we cover these situations in detail, we need to talk about another type: `RefCell`. -## `RefCell` - -Unlike `Rc`, the `RefCell` type represents single ownership over the -data that it holds. So, what makes `RefCell` different than a type like -`Box`? For that, we'll have to recall the borrowing rules we learned in -Chapter 4: - -1. At any given time, you can have either but not both of: - * One mutable reference. - * Any number of immutable references. -2. References must always be valid. - -With references, these invariants are enforced at compile time. But with -`RefCell`, these invariants are enforced *at runtime*. With references, -if you break these rules, you'll get a compiler error. With `RefCell`, -if you break these rules, you'll get a `panic!`. - -Before we talk about how to use `RefCell`, we should mention one more thing: -`RefCell` is only useful in single-threaded scenarios; it's not threadsafe. -We'll talk about concurrency and paralellism in the next chapter; for now, all -you need to know is that if you try to use `RefCell` in a single-threaded -context, you'll get a compile time error. - -### The `borrow` and `borrow_mut` methods - -With references, we use the `&` and `&mut` syntax to create references and -mutable references, respectively. But with `RefCell`, we use the `borrow` -and `borrow_mut` methods: - -```rust -use std::cell::RefCell; - -let five = RefCell::new(5); - -// we need these scopes so we don't break the rules! -{ - let r1 = five.borrow(); - let r2 = five.borrow(); - let r3 = five.borrow(); - - // r1, r2, and r3 are all immutable references. -} - -{ - let r = five.borrow_mut(); - - // r1 is a mutable reference -} -``` - -If we call both `borrow` and `borrow_mut` in the same scope, we'll get a panic. - -So why do we need `RefCell`? What good is it to enforce the rules at runtime, -instead of compile time? - -Static analysis, like Rust performs, is inherently conservative. That is, if we -accept an incorrect program, very bad things happen, but if we reject a correct -program, the programmer will be inconvenienced, but nothing catastrophic can -occur. `RefCell` is useful in two situations: - -1. When you know that the borrowing rules are respected, but when the compiler -can't understand that that's true. -2. When you need "interior mutability." - -We'll cover "interior mutability" later in this chapter, but first, let's talk -about a different kind of cell: `Cell`. - -## `Cell` - -`Cell` is the same as `RefCell`, but only for types that are `Copy`. Instead -of `borrow` and `borrow_mut` methods, it has `get` and `set` methods: - -```rust -use std::cell::Cell; - -let five = Cell::new(5); - -five.set(6); // not five any more O_O - -println!("five is: {}", five.get()); -``` - -The difference between `Cell` and `RefCell` mirrors the difference -between types that are `Copy` and types that are not; if we don't need the -ownership rules, then we can do things in a much simpler way. If we do, then we -need to deal with borrowing, rather than just copying data around. - -So when should you use `Cell`? Since we don't have the borrowing element, -the advice is the same as for `RefCell`, but only the second rule: use -`Cell` when you need interior mutability. - -But what is 'interior mutability' anyway? - ## The Interior Mutability Pattern *Interior mutability* is a design pattern in Rust for allowing you to mutate @@ -528,16 +581,18 @@ That third difference? That's interior mutability. Why are we allowed to do this? Well, to some degree, we're not. The reason we call interior mutability a "pattern" is that it's not really a language feature, it's a design pattern for libraries. More specifically, it's a pattern -that uses `unsafe` code inside to bend Rust's usual rules. We haven't yet covered -unsafe code in-depth, we will in Chapter 20. Luckily for us, you don't have to -understand how it works inside to use it. All you need to know is that the -various family of `Cell` types, as well as some others like `Mutex` (that we'll -cover in the next chapter, on concurrency) follow this pattern. +that uses `unsafe` code inside to bend Rust's usual rules. We haven't yet +covered unsafe code in-depth, we will in Chapter 20. Luckily for us, you don't +have to understand how it works inside to use it. All you need to know is that +the various family of `Cell` types, as well as some others like `Mutex` +(that we'll cover in the next chapter, on concurrency) follow this pattern. + +TODO: but no, really why are we allowed to do this, everything is meaningless now Why is this useful? Well, remember when we said that `Rc` has to store -immutable data? Given that `RefCell` is immutable, but has interior mutability, -we can combine `Rc` and `RefCell` to get a type that's both reference -counted and mutable. Like this: +immutable data? Given that `RefCell` is immutable, but has interior +mutability, we can combine `Rc` and `RefCell` to get a type that's both +reference counted and mutable. Like this: ```rust use std::rc::Rc; @@ -555,7 +610,76 @@ requires immutability, but you also need to mutate something. This comes up with types like `Rc`, but it can also come up in concurrency situations. In general, it's a fairly rare thing to need, but when you need it, it does exist. -### Cycles +## `RefCell` + +Unlike `Rc`, the `RefCell` type represents single ownership over the +data that it holds. So, what makes `RefCell` different than a type like +`Box`? For that, we'll have to recall the borrowing rules we learned in +Chapter 4: + +1. At any given time, you can have either but not both of: + * One mutable reference. + * Any number of immutable references. +2. References must always be valid. + +With references and `Box`, these invariants are enforced at compile time. +But with `RefCell`, these invariants are enforced *at runtime*. With +references, if you break these rules, you'll get a compiler error. With +`RefCell`, if you break these rules, you'll get a `panic!`. + +Static analysis, like Rust performs, is inherently conservative. That is, if we +accept an incorrect program, very bad things happen, but if we reject a correct +program, the programmer will be inconvenienced, but nothing catastrophic can +occur. `RefCell` is useful in two situations: + +1. When you know that the borrowing rules are respected, but when the compiler + can't understand that that's true. +2. When you need "interior mutability." + +// TODO: why might you want to choose your guarantees differently? +// - rustc can't reason about them (why can't it) + +Before we talk about how to use `RefCell`, we should mention one more thing: +`RefCell` is only useful in single-threaded scenarios; it's not threadsafe. +We'll talk about concurrency and paralellism in the next chapter; for now, all +you need to know is that if you try to use `RefCell` in a multi-threaded +context, you'll get a compile time error. + +### The `borrow` and `borrow_mut` methods + +With references, we use the `&` and `&mut` syntax to create references and +mutable references, respectively. But with `RefCell`, we use the `borrow` +and `borrow_mut` methods: + +```rust +use std::cell::RefCell; + +let five = RefCell::new(5); + +// we need these scopes so we don't break the rules! +{ + let r1 = five.borrow(); + let r2 = five.borrow(); + let r3 = five.borrow(); + + // r1, r2, and r3 are all immutable references. +} + +{ + let r = five.borrow_mut(); + + // r1 is a mutable reference +} +``` + +TODO: do something interesting with these + +If we call both `borrow` and `borrow_mut` in the same scope, we'll get a panic. + +So why do we need `RefCell`? What good is it to enforce the rules at runtime, +instead of compile time? + +## Leaking Memory by Creating Cycles is Safe We've shown that with `Rc`s, when the last one goes out of scope, the value is deallocated. But what about this program? @@ -581,8 +705,10 @@ fn main() { } ``` +TODO: add diagram of oh_no pointing to itself + There's a lot going on here. Fundamentally, `Cycle` is a type that contains an -`Rc`. This means that we can have a 'referene cycle', hence the name of +`Rc`. This means that we can have a 'reference cycle', hence the name of the struct. Here, we've constructed one in `main`: we have `oh_no`, and then we create a clone of it, `clone`. Since we've made a clone of it, the reference count is two: one for the initial `Rc`, and one for the clone. When `oh_no` @@ -591,17 +717,22 @@ that's it: `clone` never really goes out of scope, since it was moved into `oh_no`. This means that this memory is now unreachable, yet will never be cleaned up. It'll just sit there with a count of one, forever. In this specific case, the program ends right away, so it's not a problem, but in a -more complex program, it would be. +more complex program that allocates lots of memory in a cycle and holds onto it +for a long time, this would be a problem. -Now, as you can see, doing this is very hard. To be honest, your authors had to -look up previous discussions of an example to get this right. But it can -happen, and the way that it happens is reasonably obvious: If you have an -`Rc` that contains an `Rc`, beware. +Now, as you can see, creating reference cycles is difficult and inconvenient in +Rust. To be honest, your authors had to look up previous discussions of an +example to get this right. But it's not impossible: preventing memory leaks in +the form of reference cycles is not one of the guarantees Rust makes. In other +words, memory leaks are memory safe. If you have an `Rc` that contains an +`Rc`, be aware that you'll have to ensure that you don't create cycles on +your. One way of doing that is using `Weak`. -#### Solution: turn an Rc into a `Weak` +### Prevent Reference Cycles: Turn an `Rc` into a `Weak` -To help with this problem, the Rust standard library contains a different -type: `Weak`. Let's see what that looks like: +To help with this problem, the Rust standard library contains another smart +pointer type: `Weak`. Let's see what replacing the inner `Rc` that +`Cycle` holds with a `Weak` looks like: ```rust use std::rc::{Rc, Weak}; @@ -624,22 +755,27 @@ fn main() { } ``` -`Weak` is exactly like `Rc`, except that its reference count doesn't, well, -count when determining if something should be freed. You can turn an `Rc` into -a `Weak` with the `Rc::downgrade` associated method, which takes an `&Rc` -as an argument, and gives a `Weak` back. +`Weak` is exactly like `Rc`, except that its reference count doesn't, +well, count when determining if something should be freed. You can turn an +`Rc` into a `Weak` with the `Rc::downgrade` associated method, which +takes an `&Rc` as an argument, and gives a `Weak` back. -So in this example, when we call `oh_no.clone()`, we increment the count to two. -But when we pass that clone to `downgrade`, that count goes down again, to one. -Now, at the end of the function, when `oh_no` goes out of scope, it reduces the -count from one to zero, and the memory is freed. Success! We've broken the cycle. +TODO: print out values -If you're doing complex things with `Rc`s, you should investigate if you -have a cycle, and insert a `Weak` so that your memory doesn't leak. The -specifics depend on exactly what you're doing, but luckily, this isn't a -Rust-specific idea; all of this translates over to other reference counting -libraries in other languages, so doing some reading about it should help you. +So in this example, when we call `oh_no.clone()`, we increment the count to +two. But when we pass that clone to `downgrade`, that count goes down again, to +one. Now, at the end of the function, when `oh_no` goes out of scope, it +reduces the count from one to zero, and the memory is freed. Success! We've +broken the cycle. +TODO: what does `clone` hold after `oh_no` goes out of scope then? + +If you're doing complex things with `Rc`s, you should investigate if it's +possible for you to have a cycle, and insert a `Weak` so that you don't +create cycles and leak memory. The specifics depend on exactly what you're +doing, but luckily, this isn't a Rust-specific idea; all of this translates +over to other reference counting libraries in other languages, so doing some +reading about it should help you. ## Summary @@ -649,5 +785,5 @@ Implementing your own smart pointers is out of the scope of this book; you should check out the Nomicon if you're interested in building these kinds of abstractions. -Next, let's talk about concurrency in Rust. We'll even learn aobut a few new +Next, let's talk about concurrency in Rust. We'll even learn about a few new smart pointers that can help us with it. From 092ff982a129dd519b2fdc34c68abbf7eb9e2c29 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 23 Feb 2017 14:29:10 -0500 Subject: [PATCH 05/42] Address most comments, make more notes --- src/ch15-00-smart-pointers.md | 145 +++++++++++++++++++++------------- 1 file changed, 91 insertions(+), 54 deletions(-) diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index 8b8ea1156..9edab860e 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -27,10 +27,10 @@ kind of pointer that only borrow data; by contrast, in many cases, smart pointers *own* the data that they point to. That is, they have extra capabilities that references don't, hence the "smart" nickname. -We've actually already encounted a few smart pointers in this book, we didn't -call them that by name, though. For example, in a certian sense, `String` and +We've actually already encountered a few smart pointers in this book, we didn't +call them that by name, though. For example, in a certain sense, `String` and `Vec` from Chapter 8 are both smart pointers. They own some memory and allow -you to manipualate it. Another good example is `File`, which we used for our +you to manipulate it. Another good example is `File`, which we used for our I/O project in Chapter 12: it owns and manages a file handle that the operating system gives us. @@ -68,20 +68,20 @@ Listing 15-1: Storing an `i32` value on the heap using a box This will print `b = 5`. In this case, we can access the data in the box in a similar way as we would if this data was on the stack. Just like any value that -has ownership, when a box goes out of scope, it will be dealloacated, which +has ownership, when a box goes out of scope, it will be deallocated, which means the box (stored on the stack) and the data (stored on the heap) will both be deallocated. -Putting a single value on the heap isn't very useful, so you won't use boxes in -the way that Listing 15-1 does very often. A time when boxes are useful are -when you want to ensure that your type has a known size. For example, consider -Listing 15-2, which contains an enum definition for a *cons list*, a type of -data structure that comes from functional programming. A cons list is a list -where each item contains the next item until the end of the list, which is -signified by a value called `Nil`. Note that we aren't introducing the idea of -"nil" or "null" that we discussed in Chapter 6, this is just a regular enum -variant name we're using because it's the canonical name to use when describing -this data structure. +Putting a single value on the heap isn't very useful, so you won't use boxes by +themselves in the way that Listing 15-1 does very often. A time when boxes are +useful are when you want to ensure that your type has a known size. For +example, consider Listing 15-2, which contains an enum definition for a *cons +list*, a type of data structure that comes from functional programming. A cons +list is a list where each item contains the next item until the end of the +list, which is signified by a value called `Nil`. Note that we aren't +introducing the idea of "nil" or "null" that we discussed in Chapter 6, this is +just a regular enum variant name we're using because it's the canonical name to +use when describing this data structure.
Filename: src/main.rs @@ -181,8 +181,10 @@ The compiler did give a helpful suggestion in the error output: ``` Because a `Box` is a pointer, we always know what size it is: a `usize`, -which is the size of a pointer. So if we change our definition from Listing -15-2 to look like this: +which is the size of a pointer. The value of the `usize` will be the address of +the heap data. The heap data can be any size, but the address to the start of +that heap data will always fit in a `usize`. So if we change our definition +from Listing 15-2 to look like this: ```rust,ignore enum List { @@ -236,7 +238,9 @@ defined to hold mp3 data and metadata. `Mp3` is, in a sense, a smart pointer: it owns the `Vec` data containing the audio. In addition, it holds some optional metadata, in this case the artist and title of the song in the audio data. We want to be able to conveniently access the audio data, not the -metadata, so we implement the `Deref` trait to return the audio data: +metadata, so we implement the `Deref` trait to return the audio data. +Implementing the `Deref` trait requires implementing one method named `deref` +that borrows `self` and returns the inner data:
Filename: src/main.rs @@ -284,7 +288,7 @@ explained thoroughly yet: similarly to Chapter 13 when we looked at the Iterator trait with the `type Item`, the `type Target = T;` syntax is defining an associated type, which is covered in more detail in Chapter 20. Don't worry about that part of the example too much; it is a slightly different way of -delcaring a generic parameter. +declaring a generic parameter. In the `assert_eq!`, we're verifying that `vec![1, 2, 3]` is the result we get when dereferencing the `Mp3` instance with `*my_favorite_song`, which is what @@ -293,11 +297,30 @@ we hadn't implemented the `Deref` trait for `Mp3`, Rust wouldn't compile the code `*my_favorite_song`: we'd get an error saying type `Mp3` cannot be dereferenced. -The reason this code works is that what the `*` operator does behind the scenes -is: +The reason this code works is that what the `*` operator is doing behind +the scenes when we call `*my_favorite_song` is: -1. Call `Deref::deref(my_favorite_song)` -2. Dereference the result +TODO: which is better? +A: + +```rust,ignore +*Deref::deref(&my_favorite_song) +``` + +We borrow `my_favorite_song` and call the `Deref::deref` method + +or B: + +```rust,ignore +*(my_favorite_song.deref()) +``` + +We call the `deref` method on `my_favorite_song`, which borrows +`my_favorite_song` and returns a reference to `my_favorite_song.audio`, since +that's what we defined `deref` to do in Listing 15-4. `*` on references is +built-in, so the expansion of `*` to call `deref` doesn't recurse. So we end up +with data of type `Vec`, which matches the `vec![1, 2, 3]` in the +`assert_eq!` in Listing 15-4. The reason that the return type of the `deref` method is still a reference and why it's necessary to dereference the result of the method is that if the @@ -344,10 +367,12 @@ call `Deref::deref` as many times as it needs to in order to get a reference to match the parameter's type, when the `Deref` trait is defined for the types involved. -TODO: is there a runtime cost for this? +TODO: is there a runtime cost for this? no, the compiler resolves the indirection? -There's also a `DerefMut` trait for overriding `*` on `&mut T`s in the same -fashion that we use `Deref` to override `*` on `&T`s. +There's also a `DerefMut` trait for overriding `*` on `&mut T` for use in +assignment in the same fashion that we use `Deref` to override `*` on `&T`s. + +// TODO: insert x/y example here Rust does this kind of coercion in three cases: @@ -358,8 +383,8 @@ Rust does this kind of coercion in three cases: The first two are the same, except for mutability: if you have a `&T`, and `T` implements `Deref` to some type `U`, you can get a `&U` transparently. Same for mutable references. The last one is more tricky: if you have a mutable -reference, it will also coerece to an immutable one. The other case is _not_ -possible though: immutable references will never coerece to mutable ones. +reference, it will also coerce to an immutable one. The other case is _not_ +possible though: immutable references will never coerce to mutable ones. The reason that the `Deref` trait is important to the smart pointer pattern is that smart pointers can then be treated like regular pointers for places that @@ -401,8 +426,8 @@ BOOM! 10 fireworks explode! printed to the screen. Our message is printed, and then when `f` goes out of scope at the end of `main`, `drop` is called, and we see the message about -exploding printed. We can also use the `drop` function to call `Drop` a bit -earlier: +exploding printed. We can also use the `Drop::drop` function to call `Drop` a +bit earlier: ```rust,ignore fn main() { @@ -487,7 +512,7 @@ others defined in the standard library that add even more useful functionality. In the majority of cases, ownership is very clear: you know exactly which binding owns a given value. However, this isn't always the case; sometimes, you may actually need multiple owners. For this, Rust has a type -called `Rc`. Its name is an abbreviation for 'reference counting'. +called `Rc`. Its name is an abbreviation for *reference counting*. Reference counting is... TODO This should be used when we wish to dynamically allocate and share some data (read-only) between various portions of your program, where it is not certain @@ -533,10 +558,11 @@ fn main() { ``` This is the basic strategy: you make an `Rc` with `new`, and then call -`clone` for all of the other owners you need. When each `Rc` goes out of -scope, they decrease the count, and when the count is zero, the value is -deallocated. This strategy lets us have multiple owners, as the count will -ensure that the value remains valid as long as any of the owners still exist. +`clone` for all of the other owners you need. With each `clone`, the count goes +up by one. When each `Rc` goes out of scope, they decrease the count, and +when the count is zero, the value is deallocated. This strategy lets us have +multiple owners, as the count will ensure that the value remains valid as long +as any of the owners still exist. This idea is simple enough, but there are a few twists! Here's the first: In order for this to be okay, the data inside of an `Rc` must be immutable. If @@ -545,10 +571,9 @@ borrows to the same place can cause a lot of problems. TODO: stop here, move this later? -There's another twist, -too: an "`Rc` cycle." While single ownership is easy to reason about, -multiple owenership is a lot trickier. Before we cover these situations in -detail, we need to talk about another type: `RefCell`. +There's another twist, too: an "`Rc` cycle." While single ownership is easy +to reason about, multiple ownership is a lot trickier. Before we cover these +situations in detail, we need to talk about another type: `RefCell`. ## The Interior Mutability Pattern @@ -565,7 +590,7 @@ let mut five = 5; five = 6; // two -let five = Cell::new(5); +let five = Cell::new(5); // no mut! five.set(6); ``` @@ -582,7 +607,7 @@ Why are we allowed to do this? Well, to some degree, we're not. The reason we call interior mutability a "pattern" is that it's not really a language feature, it's a design pattern for libraries. More specifically, it's a pattern that uses `unsafe` code inside to bend Rust's usual rules. We haven't yet -covered unsafe code in-depth, we will in Chapter 20. Luckily for us, you don't +covered unsafe code, we will in Chapter 20. Luckily for us, you don't have to understand how it works inside to use it. All you need to know is that the various family of `Cell` types, as well as some others like `Mutex` (that we'll cover in the next chapter, on concurrency) follow this pattern. @@ -645,6 +670,18 @@ We'll talk about concurrency and paralellism in the next chapter; for now, all you need to know is that if you try to use `RefCell` in a multi-threaded context, you'll get a compile time error. + +1:36 PM 18:35 < aturon> steveklabnik: then i think you can just give a quick shout-out to `Cell` +1:36 PM 18:35 < nmatsakis> but without it, I feel like I would never have fixed all the bugs we +1:36 PM found :) +1:36 PM 18:35 < aturon> steveklabnik: basically: "If you're working with `Copy` types, or othewise +1:36 PM only plan to move values in and out, `Cell` is more ergonomic and lightweight" +1:36 PM 18:35 < nmatsakis> (ps I agree with that order: RefCell as dynamic borrowing, then "oh some +1:36 PM times cell works too"P) +1:36 PM 18:35 < aturon> steveklabnik: with a pointer to the `std` docs + +'Cell is like RefCell but the instead of giving references to the inner value, the value is copied in and out of the Cell'. + ### The `borrow` and `borrow_mut` methods With references, we use the `&` and `&mut` syntax to create references and @@ -707,18 +744,18 @@ fn main() { TODO: add diagram of oh_no pointing to itself -There's a lot going on here. Fundamentally, `Cycle` is a type that contains an -`Rc`. This means that we can have a 'reference cycle', hence the name of -the struct. Here, we've constructed one in `main`: we have `oh_no`, and then we -create a clone of it, `clone`. Since we've made a clone of it, the reference -count is two: one for the initial `Rc`, and one for the clone. When `oh_no` -goes out of scope at the end of `main`, it will decrement the count to one. But -that's it: `clone` never really goes out of scope, since it was moved into -`oh_no`. This means that this memory is now unreachable, yet will never be -cleaned up. It'll just sit there with a count of one, forever. In this -specific case, the program ends right away, so it's not a problem, but in a -more complex program that allocates lots of memory in a cycle and holds onto it -for a long time, this would be a problem. +There's a lot going on here. `Cycle` is a type that contains an `Rc`. +This means that we can have a 'reference cycle', hence the name of the struct. +Here, we've constructed one in `main`: we have `oh_no`, and then we create a +clone of it, `clone`. Since we've made a clone of it, the reference count is +two: one for the initial `Rc`, and one for the clone. When `oh_no` goes out +of scope at the end of `main`, it will decrement the count to one. But that's +it: `clone` never really goes out of scope, since it was moved into `oh_no`. +This means that this memory is now unreachable, yet will never be cleaned up. +It'll just sit there with a count of one, forever. In this specific case, the +program ends right away, so it's not a problem, but in a more complex program +that allocates lots of memory in a cycle and holds onto it for a long time, +this would be a problem. Now, as you can see, creating reference cycles is difficult and inconvenient in Rust. To be honest, your authors had to look up previous discussions of an @@ -756,8 +793,8 @@ fn main() { ``` `Weak` is exactly like `Rc`, except that its reference count doesn't, -well, count when determining if something should be freed. You can turn an -`Rc` into a `Weak` with the `Rc::downgrade` associated method, which +well, count when determining if something should be dropped. You can turn an +`Rc` into a `Weak` with the `Rc::downgrade` associated function, which takes an `&Rc` as an argument, and gives a `Weak` back. TODO: print out values From 54e807c1741b34792b73957685a5a48d1d9fce1c Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 23 Feb 2017 14:56:26 -0500 Subject: [PATCH 06/42] A more thorough editing pass --- src/ch15-00-smart-pointers.md | 869 +++++++++++++++++++++------------- 1 file changed, 527 insertions(+), 342 deletions(-) diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index 9edab860e..e4667c9f9 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -3,41 +3,37 @@ Now that we've learned quite a bit of Rust, we can start digging into some more complicated concepts. In this chapter, we'll learn about a design pattern in Rust called a *smart pointer*. This pattern allows us to leverage Rust's -ownership and borrowing features to manage all kinds of resources in a safe way. - -TODO: more motivation - -We'll be covering: - -* What smart pointers are -* The `Deref` and `Drop` traits -* `Box`, the simplest smart pointer -* Other common smart pointers in the standard library, like `Rc` -* A family of smart pointers called *cells* which give you *interior - mutability* - -Let's dive in! - -## Smart Pointers Own and Manage Data or Resources +ownership and borrowing features to manage all kinds of resources in a safe +way, often without much more syntax than using plain old references. So what are smart pointers, anyway? Well, we've learned about references in Rust in Chapter 4. *Pointer* is a generic programming term for something like a reference, that is, pointers "point at" data somewhere else. References are a kind of pointer that only borrow data; by contrast, in many cases, smart -pointers *own* the data that they point to. That is, they have extra -capabilities that references don't, hence the "smart" nickname. +pointers *own* the data that they point to. They also often hold metadata about +the data. Smart pointers have extra capabilities that references don't, hence +the "smart" nickname. We've actually already encountered a few smart pointers in this book, we didn't call them that by name, though. For example, in a certain sense, `String` and `Vec` from Chapter 8 are both smart pointers. They own some memory and allow -you to manipulate it. Another good example is `File`, which we used for our -I/O project in Chapter 12: it owns and manages a file handle that the operating -system gives us. +you to manipulate it, and have metadata (like their capacity) and extra +capabilities or guarantees (`String` data will always be valid UTF-8). Another +good example is `File`, which we used for our I/O project in Chapter 12: it +owns and manages a file handle that the operating system gives us, and allows +us to access the data in the file. Given that this is a general design pattern in Rust, this chapter won't cover every smart pointer that exists. Many libraries will build their own as well, and you may write some for your own code. The ones we cover here will be the -most common ones from the standard library. +most common ones from the standard library: `Box`, `Rc`, and +`RefCell`. Along the way, we'll also cover: + +* The `Deref` and `Drop` traits that make smart pointers convenient to work with +* The *interior mutability* pattern that lets you... +* Reference cycles, how they can leak memory, and how to prevent them + +Let's dive in! ## `Box` Points to Data on the Heap and Has a Known Size @@ -53,10 +49,8 @@ the heap: ```rust fn main() { let b = Box::new(5); - println!("b = {}", b); - -} // b goes out of scope here, and the data on the heap is deallocated +} ```
@@ -68,20 +62,21 @@ Listing 15-1: Storing an `i32` value on the heap using a box This will print `b = 5`. In this case, we can access the data in the box in a similar way as we would if this data was on the stack. Just like any value that -has ownership, when a box goes out of scope, it will be deallocated, which -means the box (stored on the stack) and the data (stored on the heap) will both -be deallocated. +has ownership of data, when a box goes out of scope like `b` does at the end of +`main`, it will be deallocated. The deallocation happens for both he box +(stored on the stack) and the data it points to (stored on the heap). Putting a single value on the heap isn't very useful, so you won't use boxes by themselves in the way that Listing 15-1 does very often. A time when boxes are -useful are when you want to ensure that your type has a known size. For +useful is when you want to ensure that your type has a known size. For example, consider Listing 15-2, which contains an enum definition for a *cons -list*, a type of data structure that comes from functional programming. A cons -list is a list where each item contains the next item until the end of the -list, which is signified by a value called `Nil`. Note that we aren't -introducing the idea of "nil" or "null" that we discussed in Chapter 6, this is -just a regular enum variant name we're using because it's the canonical name to -use when describing this data structure. +list*, a type of data structure that comes from functional programming. + +A cons list is a list where each item contains a value and the next item until +the end of the list, which is signified by a value called `Nil`. Note that we +aren't introducing the idea of "nil" or "null" that we discussed in Chapter 6, +this is just a regular enum variant name we're using because it's the canonical +name to use when describing the cons list data structure.
Filename: src/main.rs @@ -122,7 +117,7 @@ However, if we try to compile the above code, we get the error shown in Listing ```text error[E0072]: recursive type `List` has infinite size - --> src/main.rs:1:1 + --> | 1 | enum List { | _^ starting here... @@ -145,8 +140,10 @@ Listing 15-3: The error we get when attempting to define a recursive enum The error says this type 'has infinite size'. Why is that? It's because we've defined `List` to have a variant that is recursive: it holds another value of itself. This means Rust can't figure out how much space it needs in order to -store a `List` value. Let's break this down a bit: recall the `Message` enum -we defined in Listing 6-2 when we discussed enum definitions in Chapter 6: +store a `List` value. Let's break this down a bit: first let's look at how +Rust decides how much space it needs to store a value of a non-recursive type. +Recall the `Message` enum we defined in Listing 6-2 when we discussed enum +definitions in Chapter 6: ```rust enum Message { @@ -163,15 +160,16 @@ any space, `Message::Move` needs enough space to store two `i32` values, and so forth. Therefore, the most space a `Message` value will need is the space it would take to store the largest of its variants. -When the Rust compiler looks at a type like the enum in Listing 15-2, it tries -to figure out how much memory is needed to store value of `List`, and starts -by looking at the `Cons` variant. The `Cons` variant holds a value of type `T` -and a value of type `List`, so it can use however much the size of `T` is -plus the size of `List`. To figure out how much memory a `List` needs, it -looks at its variants, starting with the `Cons` variant. The `Cons` variant -holds a value of type `T` and a value of type `List`, and this continues -infinitely. Rust can't figure out how much space to allocate for recursively -defined types, so the compiler gives the error in Listing 15-3. +Contrast this to what happens when the Rust compiler looks at a recursive type +like the `List` in Listing 15-2. The compiler tries to figure out how much +memory is needed to store value of `List`, and starts by looking at the +`Cons` variant. The `Cons` variant holds a value of type `T` and a value of +type `List`, so it can use however much the size of `T` is plus the size of +`List`. To figure out how much memory a `List` needs, it looks at its +variants, starting with the `Cons` variant. The `Cons` variant holds a value of +type `T` and a value of type `List`, and this continues infinitely. Rust +can't figure out how much space to allocate for recursively defined types, so +the compiler gives the error in Listing 15-3. The compiler did give a helpful suggestion in the error output: @@ -180,42 +178,66 @@ The compiler did give a helpful suggestion in the error output: make `List` representable ``` -Because a `Box` is a pointer, we always know what size it is: a `usize`, -which is the size of a pointer. The value of the `usize` will be the address of -the heap data. The heap data can be any size, but the address to the start of -that heap data will always fit in a `usize`. So if we change our definition -from Listing 15-2 to look like this: +Because a `Box` is a pointer, we always know how much space it needs: a +pointer takes up a `usize` amount of space. The value of the `usize` will be +the address of the heap data. The heap data can be any size, but the address to +the start of that heap data will always fit in a `usize`. So if we change our +definition from Listing 15-2 to look like the definition here in Listing 15-4, +and change `main` to use `Box::new` for the values inside the `Cons` variants +like so: -```rust,ignore +
+Filename: src/main.rs + +```rust enum List { Cons(T, Box>), Nil, } + +use List::{Cons, Nil}; + +fn main() { + let list = Cons(1, + Box::new(Cons(2, + Box::new(Cons(3, + Box::new(Nil)))))); +} ``` -The compiler will be able to figure out the size of a `List` value. It will -look at this type, and start by looking at the `Cons` variant. The `Cons` -variant will need the size of whatever `T` is, plus the space to store a -`usize`, since a box always has the size of a `usize`. Then it looks at the -`Nil` variant, which does not store a value, so it doesn't need any extra -memory. We've broken the infinite, recursive chain by adding in a box. This is -the main area where boxes are useful: breaking up an infinite data structure so -that the compiler can know what size it is. We'll look at another case where -Rust has data of unknown size in Chapter 17 when we discuss trait objects. +
+ +Listing 15-4: Definition of `List` that uses `Box` in order to have a +known size + +
+
+ +The compiler will be able to figure out the size it needs to store a `List` +value. Rust will look at `List`, and again start by looking at the `Cons` +variant. The `Cons` variant will need the size of whatever `T` is, plus the +space to store a `usize`, since a box always has the size of a `usize`, no +matter what it's pointing to. Then Rust looks at the `Nil` variant, which does +not store a value, so `Nil` doesn't need any space. We've broken the infinite, +recursive chain by adding in a box. This is the main area where boxes are +useful: breaking up an infinite data structure so that the compiler can know +what size it is. We'll look at another case where Rust has data of unknown size +in Chapter 17 when we discuss trait objects. Even though you won't be using boxes very often, they are a good way to -understand the smart pointer pattern. The attribute of the `Box` type that -makes it a smart pointer is that it implements two important traits: `Deref` -and `Drop`. Let's investigate how boxes use these in more detail. +understand the smart pointer pattern. Two of the aspects of `Box` that are +commonly used with smart pointers are its implementations of the `Deref` trait +and the `Drop` trait. Let's investigate how these traits work and how smart +pointers use them. ## The `Deref` Trait Allows Access to the Data Through a Reference The first important smart pointer-related trait is `Deref`, which allows us to -override the `*` operator, the dereference operator (as opposed to the -multiplication operator). Overriding `*` for smart pointers makes accessing the -data behind the smart pointer convenient, and we'll talk about what we mean by -convenient in the next section about deref coercions. Remember using `*` when -we talked about references, like this: +override `*`, the dereference operator (as opposed to the multiplication +operator). Overriding `*` for smart pointers makes accessing the data behind +the smart pointer convenient, and we'll talk about what we mean by convenient +in the next section about deref coercions. Remember using `*` when we talked +about references, like this: TODO: put this back in ch 4 @@ -233,7 +255,9 @@ assert_eq!(6, x); We use `*y` to access the data that `y` refers to, rather than `y` itself, which is a reference. -Listing 15-4 has an example of overloading `*` using `Deref` on a struct we've +END TODO + +Listing 15-5 has an example of overloading `*` using `Deref` on a struct we've defined to hold mp3 data and metadata. `Mp3` is, in a sense, a smart pointer: it owns the `Vec` data containing the audio. In addition, it holds some optional metadata, in this case the artist and title of the song in the audio @@ -245,13 +269,15 @@ that borrows `self` and returns the inner data:
Filename: src/main.rs +TODO: errors in this example aren't getting caught by mdbook test, why??? + ```rust use std::ops::Deref; struct Mp3 { audio: Vec, - artist: String, - title: String, + artist: Option, + title: Option, } impl Deref for Mp3 { @@ -266,8 +292,8 @@ fn main() { let my_favorite_song = Mp3 { // we would read the actual audio data from an mp3 file audio: vec![1, 2, 3], - artist: String::from("Nirvana"), - title: String::from("Smells Like Teen Spirit"), + artist: Some(String::from("Nirvana")), + title: Some(String::from("Smells Like Teen Spirit")), }; assert_eq!(vec![1, 2, 3], *my_favorite_song); @@ -276,15 +302,15 @@ fn main() {
-Listing 15-4: An implementation of the `Deref` trait on a struct that holds mp3 +Listing 15-5: An implementation of the `Deref` trait on a struct that holds mp3 file data and metadata
-Most of this should look familliar: a struct, a trait implementation, a main -function that creates an instance of the struct. There is one part we haven't -explained thoroughly yet: similarly to Chapter 13 when we looked at the +Most of this should look familliar: a struct, a trait implementation, and a +main function that creates an instance of the struct. There is one part we +haven't explained thoroughly yet: similarly to Chapter 13 when we looked at the Iterator trait with the `type Item`, the `type Target = T;` syntax is defining an associated type, which is covered in more detail in Chapter 20. Don't worry about that part of the example too much; it is a slightly different way of @@ -300,46 +326,33 @@ dereferenced. The reason this code works is that what the `*` operator is doing behind the scenes when we call `*my_favorite_song` is: -TODO: which is better? -A: - -```rust,ignore -*Deref::deref(&my_favorite_song) -``` - -We borrow `my_favorite_song` and call the `Deref::deref` method - -or B: - ```rust,ignore *(my_favorite_song.deref()) ``` -We call the `deref` method on `my_favorite_song`, which borrows +This calls the `deref` method on `my_favorite_song`, which borrows `my_favorite_song` and returns a reference to `my_favorite_song.audio`, since -that's what we defined `deref` to do in Listing 15-4. `*` on references is -built-in, so the expansion of `*` to call `deref` doesn't recurse. So we end up -with data of type `Vec`, which matches the `vec![1, 2, 3]` in the -`assert_eq!` in Listing 15-4. +that's what we defined `deref` to do in Listing 15-5. `*` on references is +defined to just follow the reference and return the data, so the expansion of +`*` doesn't recurse for the outer `*`. So we end up with data of type +`Vec`, which matches the `vec![1, 2, 3]` in the `assert_eq!` in Listing +15-5. The reason that the return type of the `deref` method is still a reference and why it's necessary to dereference the result of the method is that if the `deref` method returned just the value, using `*` would always take ownership. -### Implicit `deref` Coercions with Functions and Methods - -TODO: consistent spelling of `deref` coercion (`Deref` coercion? deref coercion?) +### Implicit Deref Coercions with Functions and Methods Rust tends to favor explicitness over implicitness, but one case where this -does not hold true is *`deref` coercions* of arguments to functions and -methods. A `deref` coercion will automatically convert arguments passed to -functions or methods that are references to pointers or smart pointers into -references to the pointer's contents if needed to match the types of the -parameters defined in the signature. This was added to make calling functions -and methods not need as many explicit references and dereferences with `&` and -`*`. +does not hold true is *deref coercions* of arguments to functions and methods. +A deref coercion will automatically convert references to pointers or smart +pointers, when passed to functions or methods, into references to the pointer's +contents if needed to match the types of the parameters defined in the +signature. Deref coercion was added to Rust to make calling functions and +methods not need as many explicit references and dereferences with `&` and `*`. -Using our `Mp3` struct from Listing 15-4, here's the signature of a function to +Using our `Mp3` struct from Listing 15-5, here's the signature of a function to compress mp3 audio data that takes a slice of `u8`: ```rust,ignore @@ -348,37 +361,41 @@ fn compress_mp3(audio: &[u8]) -> Vec { } ``` -Because of `deref` coercion and our implementation of the `Deref` trait on -`Mp3`, we can call this function with the data in `my_favorite_song` by using -this code: +Because of deref coercion and our implementation of the `Deref` trait on `Mp3`, +we can call this function with the data in `my_favorite_song` by using this +code: ```rust,ignore let result = compress_mp3(&my_favorite_song); ``` -Without `deref` coercsion and our `Deref` implementation, we would have to -write `compress_mp3(my_favorite_song.audio.as_slice())`. Rust knows that `Mp3` -implements the `Deref` trait and returns `&Vec` from the `deref` method. -The standard library also implements the `Deref` trait on `Vec` to return -`&[T]` from the `deref` method. So Rust will implicitly call `Deref::deref` -twice to turn `&Mp3` into `&Vec` and then into `&[T]` to match the -signature of `compress_mp3`. That means we get to do less typing! Rust will -call `Deref::deref` as many times as it needs to in order to get a reference to -match the parameter's type, when the `Deref` trait is defined for the types -involved. - -TODO: is there a runtime cost for this? no, the compiler resolves the indirection? +Without deref coercion and our `Deref` implementation on `Mp3`, we would have +to write `compress_mp3(my_favorite_song.audio.as_slice())` in order to call +`compress_mp3` with a slice of the audio data. Deref coercion means that Rust +can use its knowledge of our `Deref` implementation, namely: Rust knows that +`Mp3` implements the `Deref` trait and returns `&Vec` from the `deref` +method. Rust also knows the standard library implements the `Deref` trait on +`Vec` to return `&[T]` from the `deref` method (and we can find that out too +by looking at the API documentation for `Vec`). So, at compile time, Rust +will see that it can use `Deref::deref` twice to turn `&Mp3` into `&Vec` +and then into `&[T]` to match the signature of `compress_mp3`. That means we +get to do less typing! Rust will analyze types through `Deref::deref` as many +times as it needs to in order to get a reference to match the parameter's type, +when the `Deref` trait is defined for the types involved. The indirection is +resolved at compile time, so there is no run-time penalty for taking advantage +of deref coercion. There's also a `DerefMut` trait for overriding `*` on `&mut T` for use in assignment in the same fashion that we use `Deref` to override `*` on `&T`s. -// TODO: insert x/y example here +TODO: insert x/y example here -Rust does this kind of coercion in three cases: +Rust does deref coercion when it finds types and trait implementations in three +cases: -* From `&T` to `&U` when `T: Deref`. -* From `&mut T` to `&mut U` when `T: DerefMut`. -* From `&mut T` to `&U` when `T: Deref`. +* From `&T` to `&U` when `T: Deref`. +* From `&mut T` to `&mut U` when `T: DerefMut`. +* From `&mut T` to `&U` when `T: Deref`. The first two are the same, except for mutability: if you have a `&T`, and `T` implements `Deref` to some type `U`, you can get a `&U` transparently. Same @@ -387,306 +404,409 @@ reference, it will also coerce to an immutable one. The other case is _not_ possible though: immutable references will never coerce to mutable ones. The reason that the `Deref` trait is important to the smart pointer pattern is -that smart pointers can then be treated like regular pointers for places that -expect regular pointers. We don't have to redefine methods and functions to -take smart pointers explicitly, for example. +that smart pointers can then be treated like regular references and used in +places that expect regular references. We don't have to redefine methods and +functions to take smart pointers explicitly, for example. ## The `Drop` trait The other trait that's important to the smart pointer pattern is the `Drop` trait. `Drop` lets us run some code when a value is about to go out of scope. -Listing 15-5 shows an implementation of +This is especially useful for smart pointers that manage a resource as opposed +to those that manage memory: often resources like files or network connections +need to be closed when our code is done with them. In other languages, if we +forget to call code to close these kinds of resources, the system our code is +running on might get overloaded and crash. + +In Rust, we can specify that some code should be run when a value goes out of +scope. The compiler will insert this code automatically. That means we don't +need to remember to put this code everywhere we're done with an instance of +these types, but we still won't leak resources! + +The way we specify code should be run when a value goes out of scope is by +implementing the `Drop` trait. The `Drop` trait requires us to implement one +method named `drop` that takes a mutable reference to `self`. + +Listing 15-6 shows a `WebSocket` struct that doesn't actually connect to +anything, but it prints out `Closing the socket!` when we create the struct and +when it goes out of scope so that we can see when this code gets run: + +
+Filename: src/main.rs ```rust -struct Fireworks { - number: i32, +struct WebSocket { + uri: String, } -// Drop is in the prelude, so we don't need to import it -impl Drop for Fireworks { +impl Drop for WebSocket { fn drop(&mut self) { - println!("BOOM! {} fireworks explode!", self.number); + println!("Closing the socket!"); } } fn main() { - let f = Fireworks { number: 10 }; - println!("Fireworks created."); + let w = WebSocket { uri: String::from("http://example.com/not-real") }; + println!("WebSocket created."); println!("Wait for it..."); } ``` -When we run this program, we'll see +
+ +Listing 15-6: A `WebSocket` struct that implements the `Drop` trait, where we +could put code that would close the socket. + +
+
+ +The `Drop` trait is in the prelude, so we don't need to import it. The `drop` +method implementation calls the `println!`; this is where you'd put the actual +code needed to close the socket. In `main`, we create a new instance of +`WebSocket` then print out `WebSocket created.` to be able to see that our code +got to that point at runtime. At the end of `main`, our instance of `WebSocket` +will go out of scope. Note that we didn't call the `drop` method explicitly. + +When we run this program, we'll see: ```text -Fireworks created. +WebSocket created. Wait for it... -BOOM! 10 fireworks explode! +Closing the socket! ``` -printed to the screen. Our message is printed, and then when `f` goes out of -scope at the end of `main`, `drop` is called, and we see the message about -exploding printed. We can also use the `Drop::drop` function to call `Drop` a -bit earlier: +printed to the screen, which shows that Rust automatically called `drop` for us +when our instance went out of scope. + +We can use the `std::mem::drop` function to drop a value earlier than when it +goes out of scope. This isn't usually necessary; the whole point of the `Drop` +trait is that it's taken care of automatically for us. We'll see an example of +a case when we'll need to drop a value earlier than when it goes out of scope +in Chapter 16 when we're talking about concurrency. For now, let's just see +that it's possible, and `std::mem::drop` is in the prelude so we can just call +`drop` as shown in Listing 15-7: + +
```rust,ignore fn main() { - let f = Fireworks { number: 10 }; - println!("Fireworks created."); - drop(f); + let w = WebSocket { uri: String::from("http://example.com/not-real") }; + println!("WebSocket created."); + drop(w); println!("Wait for it..."); } ``` -This will print: +
+ +Listing 15-7: Calling `std::mem::drop` to explicitly drop a value before it +goes out of scope + +
+
+ +Running this code will print the following, showing that the destructor code is +called since `Closing the socket!` is printed between `WebSocket created.` and `Wait for it...`: ```text -Fireworks created. -BOOM! 10 fireworks explode! +WebSocket created. +Closing the socket! Wait for it... ``` -Normally, you wouldn't want to wait for fireworks _after_ they explode, but you -get the idea. +Note that we aren't allowed to call the `drop` method that we defined directly: +if we replaced `drop(w)` in Listing 15-7 with `w.drop()`, we'll get a compiler +error that says `explicit destructor calls not allowed`. TODO: why aren't we +allowed to call the drop method directly? -The ability to run some code when something goes out of scope is very powerful. -For example, here's something that looks similar to a box. This code won't -_work_, but it illustrates the concept: +The definition of `std::mem::drop` is: -```rust,ignore -struct MyBox { - data: &T, -} - -impl MyBox { - fn new(data: T) { - // allocate some memory - let mut memory = allocate_memory(); - - // copy the data into that memory - *memory = T; - - // return a box containing the reference to the memory - MyBox { - data: memory, - } - } -} - -impl Drop for MyBox { - fn drop(&mut self) { - free_memory(self.data); +```rust +pub mod std { + pub mod mem { + pub fn drop(_x: T) { } } } ``` -TODO: replace this with closing a socket and just mention that this could be used to implement a custom memory allocator? +This function is generic over any type `T`, so we can pass any value to it. The +function doesn't actually have anything in its body, so it doesn't use its +parameter. The parameter is named `_x` because the `_` is a signal to the +compiler that we're intentionally not using the parameter, so it doesn't need +to warn us that we're not using it. The reason this empty function is useful is +that `drop` takes ownership of its parameter, which means the value gets +dropped at the end of this function when it goes out of scope. +Code specified in a `Drop` trait implementation can be used for many reasons to +make cleanup convenient and safe: we could use it to create our own memory +allocator, for instance! By using the `Drop` trait and Rust's ownership system, +we can't mess up and forget to clean up, or clean up a value that's still in +use. The ownership system makes sure that we call `drop` at the right time. - -So first, we declare `MyBox` to have a reference to some data. We can't use -actual `&T` references for this, we'd use `*const T`, but we won't talk about -*raw pointer*s until Chapter 20. So for now, pretend that this works; it's the -same idea. - -In `new`, we allocate some memory by asking the operating system for it. This -function doesn't exist in Rust today, so we made up a function name, -`allocate_memory`, for it. This function would return a reference to the new -memory we've been granted. We then copy our data into it by using the `*` -operator. So after the assignment, `memory` will be pointing to a copy of our -`data`. Finally, we return our new `MyBox`, created from this memory. - -That takes care of allocation, but what about deallocation? For that, we use -`Drop`, along with another fake function: `free_memory`. This function will -return the memory back to the operating system. - -So we're automatically allocating memory in `new`, and then automatically -freeing it in `drop`. We can't mess it up. The ownership system makes sure that -we call `drop` at the right time, and things work out. - -Now that you understand the basics of smart pointers, let's talk about a few -others defined in the standard library that add even more useful functionality. +Now that we've gone over `Box` and some of the characteristics of smart +pointers, let's talk about a few other smart pointers defined in the standard +library that add different kinds of useful functionality. ## The Reference Counted Smart Pointer `Rc` In the majority of cases, ownership is very clear: you know exactly which -binding owns a given value. However, this isn't always the case; -sometimes, you may actually need multiple owners. For this, Rust has a type -called `Rc`. Its name is an abbreviation for *reference counting*. Reference counting is... TODO +variable owns a given value. However, this isn't always the case; sometimes, +you may actually need multiple owners. For this, Rust has a type called +`Rc`. Its name is an abbreviation for *reference counting*. Reference +counting means keeping track of the number of references to a value in order to +know if a value is still in use or not. If there are zero references to a +value, we know we can clean up the value without any references becoming +invalid. -This should be used when we wish to dynamically allocate and share some data -(read-only) between various portions of your program, where it is not certain -which portion will finish using the pointer last. It's a viable alternative to -&T when &T is either impossible to statically check for correctness, or creates -extremely unergonomic code where the programmer does not wish to spend the -development cost of working with. +To think about this in terms of a real-world scenario, it's like a TV in a +family room. When one person comes in the room to watch TV, they turn it on. +Others can also come in the room and watch the TV. When the last person leaves +the room, they'll turn the TV off since it's no longer being used. If someone +turns off the TV while others are still watching it, though, the people +watching the TV would get mad! -TODO: insert something like the turtle example -TODO: insert why reference counting is useful-- multiple owners may use the same data, and the data goes out of scope once all of its owners go out of scope and not before. +`Rc` is for use when we want to allocate some read-only data on the heap, +share that data between multiple parts of our program, and we can't determine +at compile time which part of our program using this data will finish using it +last. If we knew which part would finish last, we could make that part the +owner of the data and the normal ownership rules enforced at compile time would +kick in. -Let's look at an example: +Note that `Rc` is only for use in single-threaded scenarios; the next +chapter on concurrency will cover how to do reference counting in +multi-threaded programs. If you try to use `Rc` with multiple threads, +you'll get a compile-time error. -```rust -use std::rc::Rc; +### Using `Rc` to Share Data -let r1 = Rc::new(5); -let r2 = r1.clone(); +Let's return to our cons list example from Listing 15-4. In Listing 15-8, we're +going to try to use `List` as we defined it using `Box`. First we'll +create one list instance that contains 5 and then 10. Next, we want to create +two more lists: one that starts with 3 and continues on to our first list +containing 5 and 10, then another list that starts with 4 and *also* continues +on to our first list containing 5 and 10. In other words, we want two lists +that both share ownership of the third list, which conceptually will be +something like this: + +```text +b -> 3 ---v +a ------> 5 -> 10 -> Nil +c -> 4 ---^ ``` -You've seen the `clone` method previously, it's usually used for making a -complete copy of some data. With `Rc`, though, it doesn't make a full copy. -`Rc` holds a 'reference count', that is, a count of how many clones exist. -Let's look at this example in more detail: +Trying to implement this using our definition of `List` with `Box` won't +work: + +
+Filename: src/main.rs + +```rust,ignore +enum List { + Cons(T, Box>), + Nil, +} + +use List::{Cons, Nil}; + +fn main() { + let a = Cons(5, + Box::new(Cons(10, + Box::new(Nil)))); + let b = Cons(3, Box::new(a)); + let c = Cons(4, Box::new(a)); +} +``` + +
+ +Listing 15-8: Having two lists using `Box` that try to share ownership of a +third list won't work + +
+
+ +If we compile this, we get this error: + +```text +error[E0382]: use of moved value: `a` + --> src/main.rs:13:30 + | +12 | let b = Cons(3, Box::new(a)); + | - value moved here +13 | let c = Cons(4, Box::new(a)); + | ^ value used here after move + | + = note: move occurs because `a` has type `List`, which does not + implement the `Copy` trait +``` + +The `Cons` variants own the data they hold, so when we create the `b` list it +moves `a` to be owned by `b`. Then when we try to use `a` again when creating +`c`, we're not allowed to since `a` has been moved. + +We could change the definition of `Cons` to hold references instead, but then +we'd have to specify lifetime parameters and we'd have to construct elements of +a list such that every element lives at least as long as the list itself. +Otherwise, the borrow checker won't even let us compile the code. + +Instead, we can change our definition of `List` to use `Rc` instead of +`Box` as shown here in Listing 15-9: + +
+Filename: src/main.rs ```rust +enum List { + Cons(T, Rc>), + Nil, +} + +use List::{Cons, Nil}; use std::rc::Rc; fn main() { - let r1 = Rc::new(5); // here, we have an Rc with a reference count of one. - - { - let r2 = r1.clone(); // here, we increment the reference count; now both r1 and - // r2 both refer to the same 5; and we have a total count - // of two. - } - // Here, the scope is ending. r2 goes out of scope first. When it does, it - // doesn't free the 5, like a Box would; it decrements the count. So after - // r2 goes out of scope, the count is one. + let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); + let b = Cons(3, a.clone()); + let c = Cons(4, a.clone()); } -// Now, r1 goes out of scope. When it does, it decrements the count. The count -// is now zero. Since the count is zero, the value is deallocated. ``` -This is the basic strategy: you make an `Rc` with `new`, and then call -`clone` for all of the other owners you need. With each `clone`, the count goes -up by one. When each `Rc` goes out of scope, they decrease the count, and -when the count is zero, the value is deallocated. This strategy lets us have -multiple owners, as the count will ensure that the value remains valid as long -as any of the owners still exist. +
-This idea is simple enough, but there are a few twists! Here's the first: In -order for this to be okay, the data inside of an `Rc` must be immutable. If -it were mutable, we'd run into a similar problem with borrowing: two mutable -borrows to the same place can cause a lot of problems. +Listing 15-9: A definition of `List` that uses `Rc` -TODO: stop here, move this later? +
+
-There's another twist, too: an "`Rc` cycle." While single ownership is easy -to reason about, multiple ownership is a lot trickier. Before we cover these -situations in detail, we need to talk about another type: `RefCell`. +Note that we need to add a `use` statement for `Rc` because it's not in the +prelude. In `main`, we create the list holding 5 and 10 and store it in a new +`Rc` in `a`. Then when we create `b` and `c`, we call the `clone` method on `a`. + +### Cloning an `Rc` Increases the Reference Count + +We've seen the `clone` method previously, where we used it for making a +complete copy of some data. With `Rc`, though, it doesn't make a full copy. +`Rc` holds a *reference count*, that is, a count of how many clones exist. +Let's change `main` as shown in Listing 15-10 to have an inner scope around +where we create `c`, and to print out the results of the `Rc::strong_count` +associated function at various points. `Rc::strong_count` returns the reference +count of the `Rc` value we pass to it, and we'll talk about why this function +is named `strong_count` in the section later in this chapter about preventing +reference cycles. + +
+Filename: src/main.rs + +```rust +# enum List { +# Cons(T, Rc>), +# Nil, +# } +# +# use List::{Cons, Nil}; +# use std::rc::Rc; +# +fn main() { + let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); + println!("rc = {}", Rc::strong_count(&a)); + let b = Cons(3, a.clone()); + println!("rc after creating b = {}", Rc::strong_count(&a)); + { + let c = Cons(4, a.clone()); + println!("rc after creating c = {}", Rc::strong_count(&a)); + } + println!("rc after c goes out of scope = {}", Rc::strong_count(&a)); +} +``` + +
+ +Listing 15-10: Printing out the reference count + +
+
+ +This will print out: + +```text +rc = 1 +rc after creating b = 2 +rc after creating c = 3 +rc after c goes out of scope = 2 +``` + +We're able to see that `a` has an initial reference count of one. Then each +time we call `clone`, the count goes up by one. When `c` goes out of scope, the +count is decreased by one. What we can't see in this example is that when `b` +and then `a` go out of scope at the end of `main`, the count of references to +the list containing 5 and 10 is then 0, and the list is dropped. This strategy +lets us have multiple owners, as the count will ensure that the value remains +valid as long as any of the owners still exist. + +In the beginning of this section, we said that `Rc` is for read-only data, +that is, the value in an `Rc` must be immutable. If it were mutable, we'd run +into a similar problem with borrowing: two mutable borrows to the same place +can cause data races and inconsistencies. But mutating data is very useful! In +the next section, we'll discuss the interior mutability pattern and the +`RefCell` type that we can use in conjunction with an `Rc` to work with +this restriction on immutability. ## The Interior Mutability Pattern *Interior mutability* is a design pattern in Rust for allowing you to mutate -something that's immutable. Wait, what? Let's compare these two pieces of code. -What's different about them? +data that's immutable. The interior mutability pattern involves using `unsafe` +code inside a data structure to bend Rust's usual rules around mutation and +borrowing. We haven't yet covered unsafe code, we will in Chapter 20. The +`unsafe` code is then wrapped in a safe API, and the outer type is still +immutable. -```rust -use std::cell::Cell; +Let's explore this by looking at the `RefCell` type that follows the +interior mutability pattern. -// one -let mut five = 5; +### `RefCell` has Interior Mutability -five = 6; +Unlike `Rc`, the `RefCell` type represents single ownership over the data +that it holds. So, what makes `RefCell` different than a type like `Box`? +Let's recall the borrowing rules we learned in Chapter 4: -// two -let five = Cell::new(5); // no mut! - -five.set(6); -``` - -There are three things that are different: - -1. We use `5` in sample one, but `Cell::new(5)` in sample two. -2. We use `=` in sample one, but `set` in sample two. -3. `five` is mutable in sample one, but not in sample two. - -That third difference? That's interior mutability. - -Why are we allowed to do this? Well, to some degree, we're not. The reason we -call interior mutability a "pattern" is that it's not really a language -feature, it's a design pattern for libraries. More specifically, it's a pattern -that uses `unsafe` code inside to bend Rust's usual rules. We haven't yet -covered unsafe code, we will in Chapter 20. Luckily for us, you don't -have to understand how it works inside to use it. All you need to know is that -the various family of `Cell` types, as well as some others like `Mutex` -(that we'll cover in the next chapter, on concurrency) follow this pattern. - -TODO: but no, really why are we allowed to do this, everything is meaningless now - -Why is this useful? Well, remember when we said that `Rc` has to store -immutable data? Given that `RefCell` is immutable, but has interior -mutability, we can combine `Rc` and `RefCell` to get a type that's both -reference counted and mutable. Like this: - -```rust -use std::rc::Rc; -use std::cell::RefCell; - -let five = Rc::new(RefCell::new(5)); - -let other_rc = five.clone(); - -*other_rc.borrow_mut() = 6; -``` - -This is where interior mutability is useful: when you have something that -requires immutability, but you also need to mutate something. This comes up -with types like `Rc`, but it can also come up in concurrency situations. In -general, it's a fairly rare thing to need, but when you need it, it does exist. - -## `RefCell` - -Unlike `Rc`, the `RefCell` type represents single ownership over the -data that it holds. So, what makes `RefCell` different than a type like -`Box`? For that, we'll have to recall the borrowing rules we learned in -Chapter 4: - -1. At any given time, you can have either but not both of: - * One mutable reference. - * Any number of immutable references. +1. At any given time, you can have *either* but not both of: + * One mutable reference. + * Any number of immutable references. 2. References must always be valid. -With references and `Box`, these invariants are enforced at compile time. -But with `RefCell`, these invariants are enforced *at runtime*. With -references, if you break these rules, you'll get a compiler error. With +With references and `Box`, the borrowing rules' invariants are enforced at +compile time. With `RefCell`, these invariants are enforced *at runtime*. +With references, if you break these rules, you'll get a compiler error. With `RefCell`, if you break these rules, you'll get a `panic!`. -Static analysis, like Rust performs, is inherently conservative. That is, if we -accept an incorrect program, very bad things happen, but if we reject a correct -program, the programmer will be inconvenienced, but nothing catastrophic can -occur. `RefCell` is useful in two situations: +Static analysis, like Rust performs, is inherently conservative. That is, if +Rust accepts an incorrect program, people would not be able to trust in the +guarantees Rust makes. If Rust rejects a correct program, the programmer will +be inconvenienced, but nothing catastrophic can occur. `RefCell` is useful +in two situations: 1. When you know that the borrowing rules are respected, but when the compiler can't understand that that's true. -2. When you need "interior mutability." +2. When you need interior mutability. -// TODO: why might you want to choose your guarantees differently? -// - rustc can't reason about them (why can't it) - -Before we talk about how to use `RefCell`, we should mention one more thing: -`RefCell` is only useful in single-threaded scenarios; it's not threadsafe. -We'll talk about concurrency and paralellism in the next chapter; for now, all -you need to know is that if you try to use `RefCell` in a multi-threaded +Similarly to `Rc`, `RefCell` is only for use in single-threaded +scenarios. We'll talk about how to get the functionality of `RefCell` in a +multi-threaded program in the next chapter on concurrency. For now, all you +need to know is that if you try to use `RefCell` in a multi-threaded context, you'll get a compile time error. - -1:36 PM 18:35 < aturon> steveklabnik: then i think you can just give a quick shout-out to `Cell` -1:36 PM 18:35 < nmatsakis> but without it, I feel like I would never have fixed all the bugs we -1:36 PM found :) -1:36 PM 18:35 < aturon> steveklabnik: basically: "If you're working with `Copy` types, or othewise -1:36 PM only plan to move values in and out, `Cell` is more ergonomic and lightweight" -1:36 PM 18:35 < nmatsakis> (ps I agree with that order: RefCell as dynamic borrowing, then "oh some -1:36 PM times cell works too"P) -1:36 PM 18:35 < aturon> steveklabnik: with a pointer to the `std` docs - -'Cell is like RefCell but the instead of giving references to the inner value, the value is copied in and out of the Cell'. - -### The `borrow` and `borrow_mut` methods - With references, we use the `&` and `&mut` syntax to create references and mutable references, respectively. But with `RefCell`, we use the `borrow` -and `borrow_mut` methods: +and `borrow_mut` methods, which are part of the safe API that `RefCell` has. + +Listing 15-11 shows what mutating a value inside an immutable `RefCell` +looks like: + +~~~~ Carol is still in the process of editing beyond this point ~~~~ + + + + ```rust use std::cell::RefCell; @@ -716,7 +836,65 @@ If we call both `borrow` and `borrow_mut` in the same scope, we'll get a panic. So why do we need `RefCell`? What good is it to enforce the rules at runtime, instead of compile time? -## Leaking Memory by Creating Cycles is Safe + + + + + + + + + + +Why is this useful? Well, remember when we said that `Rc` has to store +immutable data? Given that `RefCell` is immutable, but has interior +mutability, we can combine `Rc` and `RefCell` to get a type that's both +reference counted and mutable. Like this: + +```rust +use std::rc::Rc; +use std::cell::RefCell; + +let five = Rc::new(RefCell::new(5)); + +let other_rc = five.clone(); + +*other_rc.borrow_mut() = 6; +``` + +This is where interior mutability is useful: when you have something that +requires immutability, but you also need to mutate something. This comes up +with types like `Rc`, but it can also come up in concurrency situations. In +general, it's a fairly rare thing to need, but when you need it, it does exist. + + + + +There are other types with interior mutability that are similar to `RefCell`: for example, `Cell` + +1:36 PM 18:35 < aturon> steveklabnik: then i think you can just give a quick shout-out to `Cell` +1:36 PM 18:35 < nmatsakis> but without it, I feel like I would never have fixed all the bugs we +1:36 PM found :) +1:36 PM 18:35 < aturon> steveklabnik: basically: "If you're working with `Copy` types, or othewise +1:36 PM only plan to move values in and out, `Cell` is more ergonomic and lightweight" +1:36 PM 18:35 < nmatsakis> (ps I agree with that order: RefCell as dynamic borrowing, then "oh some +1:36 PM times cell works too"P) +1:36 PM 18:35 < aturon> steveklabnik: with a pointer to the `std` docs + +'Cell is like RefCell but the instead of giving references to the inner value, the value is copied in and out of the Cell'. + +All you need to know is that +the various family of `Cell` types, as well as some others like `Mutex` +(that we'll cover in the next chapter, on concurrency) follow this pattern. + + + +## Creating Reference Cycles and Leaking Memory is Safe + +A twist to `Rc` is that it's possible to create cycles of references. This +is bad because the reference count of each item in the cycle will never reach +0, and the values will never be dropped. Let's take a look at how that might +happen and how to prevent it. We've shown that with `Rc`s, when the last one goes out of scope, the value is deallocated. But what about this program? @@ -814,6 +992,13 @@ doing, but luckily, this isn't a Rust-specific idea; all of this translates over to other reference counting libraries in other languages, so doing some reading about it should help you. + + + + + + + ## Summary Whew! Smart pointers are powerful, but complex. We've covered the basics of From 12e12c89bd8946407662e5bb1485a18efc466fb6 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Sat, 25 Feb 2017 16:54:51 -0500 Subject: [PATCH 07/42] More edits --- src/ch15-00-smart-pointers.md | 228 +++++++++++++++++++++++++--------- 1 file changed, 168 insertions(+), 60 deletions(-) diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index e4667c9f9..4ae843570 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -506,7 +506,8 @@ goes out of scope
Running this code will print the following, showing that the destructor code is -called since `Closing the socket!` is printed between `WebSocket created.` and `Wait for it...`: +called since `Closing the socket!` is printed between `WebSocket created.` and +`Wait for it...`: ```text WebSocket created. @@ -779,11 +780,11 @@ compile time. With `RefCell`, these invariants are enforced *at runtime*. With references, if you break these rules, you'll get a compiler error. With `RefCell`, if you break these rules, you'll get a `panic!`. -Static analysis, like Rust performs, is inherently conservative. That is, if -Rust accepts an incorrect program, people would not be able to trust in the -guarantees Rust makes. If Rust rejects a correct program, the programmer will -be inconvenienced, but nothing catastrophic can occur. `RefCell` is useful -in two situations: +Static analysis, like the Rust compiler performs, is inherently conservative. +That is, if Rust accepts an incorrect program, people would not be able to +trust in the guarantees Rust makes. If Rust rejects a correct program, the +programmer will be inconvenienced, but nothing catastrophic can occur. +`RefCell` is useful in two situations: 1. When you know that the borrowing rules are respected, but when the compiler can't understand that that's true. @@ -799,102 +800,210 @@ With references, we use the `&` and `&mut` syntax to create references and mutable references, respectively. But with `RefCell`, we use the `borrow` and `borrow_mut` methods, which are part of the safe API that `RefCell` has. -Listing 15-11 shows what mutating a value inside an immutable `RefCell` -looks like: - -~~~~ Carol is still in the process of editing beyond this point ~~~~ - - - +Listing 15-11 shows what it looks like to use `RefCell` with functions that +borrow their parameters immutably and mutably. Note that the `data` variable is +declared as immutable with `let data` rather than `let mut data`, yet we're +allowed to mutate the value by using `a_fn_that_mutably_borrows`! +
+Filename: src/main.rs ```rust use std::cell::RefCell; -let five = RefCell::new(5); - -// we need these scopes so we don't break the rules! -{ - let r1 = five.borrow(); - let r2 = five.borrow(); - let r3 = five.borrow(); - - // r1, r2, and r3 are all immutable references. +fn a_fn_that_immutably_borrows(a: &i32) { + println!("a is {}", a); } -{ - let r = five.borrow_mut(); +fn a_fn_that_mutably_borrows(b: &mut i32) { + *b += 1; +} - // r1 is a mutable reference +fn main() { + let data = RefCell::new(5); + a_fn_that_immutably_borrows(&data.borrow()); + a_fn_that_mutably_borrows(&mut data.borrow_mut()); + a_fn_that_immutably_borrows(&data.borrow()); } ``` -TODO: do something interesting with these +
-If we call both `borrow` and `borrow_mut` in the same scope, we'll get a panic. +Listing 15-11: Using `RefCell`, `borrow`, and `borrow_mut` -So why do we need `RefCell`? What good is it to enforce the rules at runtime, -instead of compile time? +
+
+This example prints: +```text +a is 5 +a is 6 +``` +Here, we've created a new `RefCell` containing the value 5. We can get an +immutable reference to the value inside the `RefCell` by calling the `borrow` +method. More interestingly, we can get a mutable reference to the value inside +the `RefCell` with the `borrow_mut` method, and the function +`a_fn_that_mutably_borrows` is allowed to change the value. We can see that the +next time we print out the value, it's 6 instead of 5. +Recall that because of the borrowing rules, this code trying to create two +mutable borrows in the same scope won't compile: +```rust,ignore +let mut s = String::from("hello"); +let r1 = &mut s; +let r2 = &mut s; +``` +We'll get this compiler error: +```text +error[E0499]: cannot borrow `s` as mutable more than once at a time + --> + | +5 | let r1 = &mut s; + | - first mutable borrow occurs here +6 | let r2 = &mut s; + | ^ second mutable borrow occurs here +7 | } + | - first borrow ends here +``` +In contrast, using `RefCell` and calling `borrow_mut` twice in the same +scope *will* compile, but it will panic at runtime instead. This code: +```rust,ignore +use std::cell::RefCell; -Why is this useful? Well, remember when we said that `Rc` has to store -immutable data? Given that `RefCell` is immutable, but has interior -mutability, we can combine `Rc` and `RefCell` to get a type that's both -reference counted and mutable. Like this: +fn main() { + let mut s = RefCell::new(String::from("hello")); + + let r1 = s.borrow_mut(); + let r2 = s.borrow_mut(); +} +``` + +compiles but panics with the following error when we `cargo run`: + +```text + Finished dev [unoptimized + debuginfo] target(s) in 0.83 secs + Running `target/debug/refcell` +thread 'main' panicked at 'already borrowed: BorrowMutError', +/stable-dist-rustc/build/src/libcore/result.rs:868 +note: Run with `RUST_BACKTRACE=1` for a backtrace. +``` + +This runtime `BorrowMutError` is similar to the compiler error: it says we've +already borrowed `s` mutably once, so we're not allowed to borrow it again. We +aren't getting around the borrowing rules, we're just choosing to have Rust +enforce them at runtime instead of compile time. You could choose to use +`RefCell` everywhere all the time, but in addition to having to type +`RefCell` a lot, you'd find out about possible problems later (possibly in +production rather than during development). Also, checking the borrowing rules +while your program is running has a performance penalty. + +So why would we choose to make the tradeoffs that using `RefCell` involves? +Well, remember when we said that `Rc` has to store immutable data? Given +that `RefCell` is immutable, but has interior mutability, we can combine +`Rc` and `RefCell` to get a type that's both reference counted and +mutable. Listing 15-12 shows an example of how to do that, again going back to +our cons list from Listing 15-9. In this example, the type we're filling in for +`T` is `Rc>`: + +
+Filename: src/main.rs ```rust +#[derive(Debug)] +enum List { + Cons(T, Rc>), + Nil, +} + +use List::{Cons, Nil}; use std::rc::Rc; use std::cell::RefCell; -let five = Rc::new(RefCell::new(5)); +fn main() { + let value = Rc::new(RefCell::new(5)); -let other_rc = five.clone(); + let a = Cons(value.clone(), Rc::new(Nil)); + let shared_list = Rc::new(a); -*other_rc.borrow_mut() = 6; + let b = Cons(Rc::new(RefCell::new(6)), shared_list.clone()); + let c = Cons(Rc::new(RefCell::new(10)), shared_list.clone()); + + *value.borrow_mut() += 10; + + println!("shared_list after = {:?}", shared_list); + println!("b after = {:?}", b); + println!("c after = {:?}", c); +} ``` -This is where interior mutability is useful: when you have something that -requires immutability, but you also need to mutate something. This comes up -with types like `Rc`, but it can also come up in concurrency situations. In -general, it's a fairly rare thing to need, but when you need it, it does exist. +
+Listing 15-12: Using `Rc>` to create a `List` that we can mutate +
+
+We're creating a value, which is an instance of `T`. We're storing it in a +variable named `value` because we want to be able to access it directly later. +Then we create a `List` in `a` that has a `Cons` variant that holds `value`, +and `value` needs to be cloned since we want `value` to also have ownership in +addition to `a`. Then we wrap `a` in an `Rc` so that we can create lists `b` +and `c` that start differently but both refer to `a`, similarly to what we did +in Listing 15-9. -There are other types with interior mutability that are similar to `RefCell`: for example, `Cell` +Once we have the lists in `shared_list`, `b`, and `c` created, then we add 10 +to the 5 in `value` by dereferencing the `Rc` and calling `borrow_mut` on +the `RefCell`. -1:36 PM 18:35 < aturon> steveklabnik: then i think you can just give a quick shout-out to `Cell` -1:36 PM 18:35 < nmatsakis> but without it, I feel like I would never have fixed all the bugs we -1:36 PM found :) -1:36 PM 18:35 < aturon> steveklabnik: basically: "If you're working with `Copy` types, or othewise -1:36 PM only plan to move values in and out, `Cell` is more ergonomic and lightweight" -1:36 PM 18:35 < nmatsakis> (ps I agree with that order: RefCell as dynamic borrowing, then "oh some -1:36 PM times cell works too"P) -1:36 PM 18:35 < aturon> steveklabnik: with a pointer to the `std` docs +When we print out `shared_list`, `b`, and `c`, we can see that they all have +the modified value of 15: -'Cell is like RefCell but the instead of giving references to the inner value, the value is copied in and out of the Cell'. - -All you need to know is that -the various family of `Cell` types, as well as some others like `Mutex` -(that we'll cover in the next chapter, on concurrency) follow this pattern. +```text +shared_list after = Cons(RefCell { value: 15 }, Nil) +b after = Cons(RefCell { value: 6 }, Cons(RefCell { value: 15 }, Nil)) +c after = Cons(RefCell { value: 10 }, Cons(RefCell { value: 15 }, Nil)) +``` +This is pretty neat! We didn't have to modify our definition of `List` at +all, since the generic parameter lets us substitute any immutable type. By +using `RefCell`, we satisfy the immutable type requirement since +`RefCell` is outwardly immutable, but we can use the methods on `RefCell` +that provide access to its interior mutability to be able to modify our data +when we need to. The runtime checks of the borrowing rules that `RefCell` +does protect us from data races, and we've decided that we want to trade a bit +of speed for the flexibility in our data structures. +`RefCell` is not the only standard library type that provides interior +mutability. `Cell` is similar but instead of giving references to the inner +value like `RefCell` does, the value is copied in and out of the `Cell`. +`Mutex` offers interior mutability that is safe to use across threads, and +we'll be discussing its use in the next chapter on concurrency. Check out the +standard library docs for more details on the differences between these types. ## Creating Reference Cycles and Leaking Memory is Safe -A twist to `Rc` is that it's possible to create cycles of references. This -is bad because the reference count of each item in the cycle will never reach -0, and the values will never be dropped. Let's take a look at how that might -happen and how to prevent it. +Rust makes a number of guarantees that we've talked about, for example that +we'll never have a null value, and data races will be disallowed at compile +time. Rust's memory safety guarantees make it more difficult to create memory +that never gets cleaned up, which is known as a *memory leak*. Rust does not +make memory leaks *impossible*, however, preventing memory leaks is *not* one +of Rust's guarantees. In other words, memory leaks are memory safe. + +By using `Rc` and `RefCell`, it is possible to create cycles of +references where items refer to each other in a cycle. This is bad because the +reference count of each item in the cycle will never reach 0, and the values +will never be dropped. Let's take a look at how that might happen and how to +prevent it. + +In Listing 15-13, we're going to create We've shown that with `Rc`s, when the last one goes out of scope, the value is deallocated. But what about this program? @@ -938,8 +1047,7 @@ this would be a problem. Now, as you can see, creating reference cycles is difficult and inconvenient in Rust. To be honest, your authors had to look up previous discussions of an example to get this right. But it's not impossible: preventing memory leaks in -the form of reference cycles is not one of the guarantees Rust makes. In other -words, memory leaks are memory safe. If you have an `Rc` that contains an +the form of reference cycles is not one of the guarantees Rust makes. If you have an `Rc` that contains an `Rc`, be aware that you'll have to ensure that you don't create cycles on your. One way of doing that is using `Weak`. From b07ce30dcfb6ea6e1201e8ed59a843721686651b Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Sun, 26 Feb 2017 13:36:41 -0500 Subject: [PATCH 08/42] All but the summary --- src/ch15-00-smart-pointers.md | 304 ++++++++++++++++++++++++++-------- 1 file changed, 234 insertions(+), 70 deletions(-) diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index 4ae843570..c9747dc77 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -1003,95 +1003,266 @@ reference count of each item in the cycle will never reach 0, and the values will never be dropped. Let's take a look at how that might happen and how to prevent it. -In Listing 15-13, we're going to create +In Listing 15-13, we're going to continue building on the `List` definition +from Listing 15-12. We've added a `RefCell` to the `Cons` variant's definition +so that we can modify a `Cons` instance after we've created it. We've also +added a `next_item` method to make it convenient for us to access the second +item, if we have a `Cons` variant: -We've shown that with `Rc`s, when the last one goes out of scope, the value -is deallocated. But what about this program? +
+Filename: src/main.rs ```rust -use std::rc::Rc; -use std::cell::RefCell; - -struct Cycle { - really_bad: RefCell>>, - leaked_data: i32, +#[derive(Debug)] +enum List { + Cons(T, RefCell>>), + Nil, } -fn main() { - let mut oh_no = Rc::new(Cycle { - really_bad: RefCell::new(None), - leaked_data: 5, - }); - - let clone = oh_no.clone(); - - *oh_no.really_bad.borrow_mut() = Some(clone); +impl List { + fn next_item(&self) -> Option<&RefCell>>> { + match *self { + Cons(_, ref item) => Some(item), + Nil => None, + } + } } ``` -TODO: add diagram of oh_no pointing to itself +
-There's a lot going on here. `Cycle` is a type that contains an `Rc`. -This means that we can have a 'reference cycle', hence the name of the struct. -Here, we've constructed one in `main`: we have `oh_no`, and then we create a -clone of it, `clone`. Since we've made a clone of it, the reference count is -two: one for the initial `Rc`, and one for the clone. When `oh_no` goes out -of scope at the end of `main`, it will decrement the count to one. But that's -it: `clone` never really goes out of scope, since it was moved into `oh_no`. -This means that this memory is now unreachable, yet will never be cleaned up. -It'll just sit there with a count of one, forever. In this specific case, the -program ends right away, so it's not a problem, but in a more complex program -that allocates lots of memory in a cycle and holds onto it for a long time, -this would be a problem. +Listing 15-13: A cons list definition that holds a `RefCell` so that we can +modify what a `Cons` variant is referring to + +
+
+ +TODO: insert diagram showing the "shape" of the `Cons` variant? + +Next, in Listing 15-14, we're going to create a `List` value in the variable +`a` that initially is a list of `5, Nil`. Then we'll create a `List` value +in the variable `b` that is a list of the value 10 and then points to the list +in `a`. Finally, we'll modify `a` so that it points to `b` instead of `Nil`, +which will then create a cycle: + +
+Filename: src/main.rs + +```rust +# #[derive(Debug)] +# enum List { +# Cons(T, RefCell>>), +# Nil, +# } +# +# impl List { +# fn next_item(&self) -> Option<&RefCell>>> { +# match *self { +# Cons(_, ref item) => Some(item), +# Nil => None, +# } +# } +# } +# +use List::{Cons, Nil}; +use std::rc::Rc; +use std::cell::RefCell; + +fn main() { + + let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); + + println!("a initial rc count = {}", Rc::strong_count(&a)); + println!("a next item = {:?}", a.next_item()); + + let b = Rc::new(Cons(10, RefCell::new(a.clone()))); + + println!("a rc count after b creation = {}", Rc::strong_count(&a)); + println!("b initial rc count = {}", Rc::strong_count(&b)); + println!("b next item = {:?}", b.next_item()); + + if let Some(ref link) = a.next_item() { + *link.borrow_mut() = b.clone(); + } + + println!("b rc count after changing a = {}", Rc::strong_count(&b)); + println!("a rc count after changing a = {}", Rc::strong_count(&a)); + + // Uncomment the next line to see that we have a cycle; it will + // overflow the stack + // println!("a next item = {:?}", a.next_item()); +} +``` + +
+ +Listing 15-14: Creating a reference cycle of two `List` values pointing to +each other + +
+
+ +We use the `next_item` method to get a reference to the `RefCell` in `a`, which +we put in the variable `link`. Then we use the `borrow_mut` method on the +`RefCell` to change the value inside from an `Rc` that holds a `Nil` value to +the `Rc` in `b`. We've created a reference cycle that looks like: + +TODO: insert diagram showing b and a pointing to each other + +If you uncomment the last `println!`, Rust will try and print this cycle out +with `a` pointing to `b` pointing to `a` and so forth until it overflows the +stack. + +Looking at the results of the `println!` calls before the last one, we'll see +that the reference count of both `a` and `b` are 2 after we change `a` to point +to `b`. At the end of `main`, Rust will try and drop `b` first, which will +decrease the count of the `Rc` by one. However, because `a` is still +referencing that `Rc`, its count is 1 rather than 0, so the memory the `Rc` has +on the heap won't be dropped. It'll just sit there with a count of one, +forever. In this specific case, the program ends right away, so it's not a +problem, but in a more complex program that allocates lots of memory in a cycle +and holds onto it for a long time, this would be a problem. The program would +be using more memory than it needs to be, and might overwhelm the system and +cause it to run out of memory available to use. Now, as you can see, creating reference cycles is difficult and inconvenient in Rust. To be honest, your authors had to look up previous discussions of an example to get this right. But it's not impossible: preventing memory leaks in -the form of reference cycles is not one of the guarantees Rust makes. If you have an `Rc` that contains an -`Rc`, be aware that you'll have to ensure that you don't create cycles on -your. One way of doing that is using `Weak`. +the form of reference cycles is not one of the guarantees Rust makes. If you +have `RefCell` values that contain `Rc` values or similar nested +combinations of types with interior mutability and reference counting, be aware +that you'll have to ensure that you don't create cycles on your. One way of +doing that is using `Weak`. ### Prevent Reference Cycles: Turn an `Rc` into a `Weak` To help with this problem, the Rust standard library contains another smart -pointer type: `Weak`. Let's see what replacing the inner `Rc` that -`Cycle` holds with a `Weak` looks like: +pointer type: `Weak`. We've been showing how cloning an `Rc` increases +the `strong_count` of references; `Weak` is a way to reference an `Rc` +that does not increment the `strong_count`: instead it increments the +`weak_count` of references to an `Rc`. When an `Rc` goes out of scope, the +inner value will get dropped if the `strong_count` is 0, even if the +`weak_count` is not 0. When we attempt to use a `Weak` reference, we'll get +an `Option` that will be `Some` if the `Rc` value has not been dropped yet, +and `None` if the `Rc` value has been dropped. + +So in order to make it possible to create lists that point to each other but not create reference cycles, in Listing 15-15, we're going to change our definition of `List` again to hold a `Weak` instead of an `Rc`. + +
+Filename: src/main.rs ```rust -use std::rc::{Rc, Weak}; -use std::cell::RefCell; - -struct Cycle { - really_bad: RefCell>>, - leaked_data: i32, +#[derive(Debug)] +enum List { + Cons(T, RefCell>>), + Nil, } -fn main() { - let mut oh_no = Rc::new(Cycle { - really_bad: RefCell::new(None), - leaked_data: 5, - }); - - let clone = Rc::downgrade(&oh_no.clone()); - - *oh_no.really_bad.borrow_mut() = Some(clone); +impl List { + fn next_item(&self) -> Option>> { + match *self { + Cons(_, ref n) => (&*n.borrow()).upgrade(), + Nil => None, + } + } } ``` -`Weak` is exactly like `Rc`, except that its reference count doesn't, -well, count when determining if something should be dropped. You can turn an -`Rc` into a `Weak` with the `Rc::downgrade` associated function, which -takes an `&Rc` as an argument, and gives a `Weak` back. +
-TODO: print out values +Listing 15-15: Modifying `List` to have `Weak` references instead of +`Rc` -So in this example, when we call `oh_no.clone()`, we increment the count to -two. But when we pass that clone to `downgrade`, that count goes down again, to -one. Now, at the end of the function, when `oh_no` goes out of scope, it -reduces the count from one to zero, and the memory is freed. Success! We've -broken the cycle. +
+
-TODO: what does `clone` hold after `oh_no` goes out of scope then? +We've also modified the `next_item` method: not only does it return `None` when +`self` is `Nil` and doesn't have a `next_item`, it now also returns `None` if +the value that the `Weak` references has been dropped. The `upgrade` method +on a `Weak` value returns `Some` containing an `Rc` if the value has not yet +been dropped and `None` if the value has been dropped. + +TODO: is this bad software design, collapsing two cases that return `None` like this??? + +To create `Weak` values, we call the `Rc::downgrade` associated function, +which takes an `&Rc` as an argument, and gives a `Weak` back. + +Listing 15-16 shows a `main` method where we're trying to create `a` and `b` lists that point to each other, similarly to what we did in Listing 15-14, but this time we won't have a reference cycle and the values will be dropped when they go out of scope at the end of `main`: + +
+ +```rust +# #[derive(Debug)] +# enum List { +# Cons(T, RefCell>>), +# Nil, +# } +# +# impl List { +# fn next_item(&self) -> Option>> { +# match *self { +# Cons(_, ref n) => (&*n.borrow()).upgrade(), +# Nil => None, +# } +# } +# } +# +use List::{Cons, Nil}; +use std::rc::{Rc, Weak}; +use std::cell::RefCell; + +fn main() { + let nil = Rc::new(Nil); + + let a = Rc::new(Cons(5, RefCell::new(Rc::downgrade(&nil)))); + + println!("a.next_item() = {:?}", a.next_item()); + + { + let b = Rc::new(Cons(10, RefCell::new(Rc::downgrade(&a.clone())))); + + if let Cons(_, ref link) = *a { + *link.borrow_mut() = Rc::downgrade(&b.clone()); + } + + println!("a.next_item() = {:?}", a.next_item()); + println!("b.next_item() = {:?}", b.next_item()); + } + + println!("a.next_item() = {:?}", a.next_item()); +} +``` + +
+ +Listing 15-16: Creating `List` values using weak references + +
+
+ +First, we create a variable for the `Rc` that holds the `Nil` value, so that +it's clearer to see that we call `Rc::downgrade` and pass a reference to `nil` +when we create `a`. At that point, we print out the value of `a.next_item()` +and we can see that it's `Some(Nil)`. + +We've added an inner scope in order to demonstrate what happens when `b` goes +out of scope. In the inner scope, we create `b` that has a weak reference to +`a`, and then we modify `a` to have a weak reference to `b` instead of to +`nil`. At the end of the inner scope, we can see that `a` and `b` are pointing +to each other, but through weak references. + +At the end of the inner scope, `b` goes out of scope. The value that the +`Rc` in `b` holds gets dropped, even though `a` still references it, because +the reference in `a` is a weak reference that doesn't count when Rust decides +whether the value in `b` should be dropped or not. At the end of `main` when we +print out `a.next_item()` again, we can see that we now get a `None` value +since the value that the weak reference in `a` was pointing to has been +dropped. Success! We've broken the cycle. + +Add some `println!` statements at various places that display the values that +`Rc::strong_count` and `Rc::weak_count` return for `a` and `b` at different +points in this example to see which parts of the code increase or decrease the +strong or weak counts. If you're doing complex things with `Rc`s, you should investigate if it's possible for you to have a cycle, and insert a `Weak` so that you don't @@ -1100,19 +1271,12 @@ doing, but luckily, this isn't a Rust-specific idea; all of this translates over to other reference counting libraries in other languages, so doing some reading about it should help you. - - - - - - - ## Summary Whew! Smart pointers are powerful, but complex. We've covered the basics of smart pointers, and how to use some of the most common smart pointers. Implementing your own smart pointers is out of the scope of this book; you -should check out the Nomicon if you're interested in building these kinds of +should check out the [Nomicon] if you're interested in building these kinds of abstractions. Next, let's talk about concurrency in Rust. We'll even learn about a few new From 3af06ba7eef70719575acb4400663a2e1d82ac64 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Sun, 26 Feb 2017 19:30:29 -0500 Subject: [PATCH 09/42] Whew. Finish editing. --- dictionary.txt | 11 +++++++++++ src/ch15-00-smart-pointers.md | 34 ++++++++++++++++++++++------------ 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/dictionary.txt b/dictionary.txt index 35786ec10..37bc86106 100644 --- a/dictionary.txt +++ b/dictionary.txt @@ -31,6 +31,7 @@ bool boolean booleans Bors +BorrowMutError BuildHasher Cagain callsite @@ -54,14 +55,18 @@ ctrl Ctrl deallocated deallocating +deallocation debuginfo deps deref Deref dereference Dereference +dereferenced +dereferences dereferencing DerefMut +destructor destructure destructuring Destructuring @@ -197,10 +202,12 @@ RAII randcrate READMEs rect +recurse redeclaring Refactoring refactor refactoring +refcell RefCell repr retweet @@ -264,6 +271,8 @@ typeof UFCS unary Unary +uncomment +Uncomment Uninstalling uninstall unoptimized @@ -276,11 +285,13 @@ usize UsState utils variable's +variant's vers versa Versioning wasn WeatherForecast +WebSocket whitespace wildcards workspace diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index c9747dc77..6148f769d 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -269,8 +269,6 @@ that borrows `self` and returns the inner data:
Filename: src/main.rs -TODO: errors in this example aren't getting caught by mdbook test, why??? - ```rust use std::ops::Deref; @@ -308,7 +306,7 @@ file data and metadata
-Most of this should look familliar: a struct, a trait implementation, and a +Most of this should look familiar: a struct, a trait implementation, and a main function that creates an instance of the struct. There is one part we haven't explained thoroughly yet: similarly to Chapter 13 when we looked at the Iterator trait with the `type Item`, the `type Target = T;` syntax is defining @@ -408,7 +406,7 @@ that smart pointers can then be treated like regular references and used in places that expect regular references. We don't have to redefine methods and functions to take smart pointers explicitly, for example. -## The `Drop` trait +## The `Drop` Trait The other trait that's important to the smart pointer pattern is the `Drop` trait. `Drop` lets us run some code when a value is about to go out of scope. @@ -575,7 +573,7 @@ kick in. Note that `Rc` is only for use in single-threaded scenarios; the next chapter on concurrency will cover how to do reference counting in -multi-threaded programs. If you try to use `Rc` with multiple threads, +multithreaded programs. If you try to use `Rc` with multiple threads, you'll get a compile-time error. ### Using `Rc` to Share Data @@ -792,8 +790,8 @@ programmer will be inconvenienced, but nothing catastrophic can occur. Similarly to `Rc`, `RefCell` is only for use in single-threaded scenarios. We'll talk about how to get the functionality of `RefCell` in a -multi-threaded program in the next chapter on concurrency. For now, all you -need to know is that if you try to use `RefCell` in a multi-threaded +multithreaded program in the next chapter on concurrency. For now, all you +need to know is that if you try to use `RefCell` in a multithreaded context, you'll get a compile time error. With references, we use the `&` and `&mut` syntax to create references and @@ -1273,11 +1271,23 @@ reading about it should help you. ## Summary -Whew! Smart pointers are powerful, but complex. We've covered the basics of -smart pointers, and how to use some of the most common smart pointers. -Implementing your own smart pointers is out of the scope of this book; you -should check out the [Nomicon] if you're interested in building these kinds of -abstractions. +We've now covered how you can use different kinds of smart pointers to choose +different guarantees and tradeoffs than those Rust makes with regular +references. `Box` has a known size and points to data allocated on the heap. +`Rc` keeps track of the number of references to data on the heap so that +data can have multiple owners. `RefCell` with its interior mutability gives +us a type that can be used where we need an immutable type, and enforces the +borrowing rules at runtime instead of at compile time. + +We've also discussed the `Deref` and `Drop` traits that enable a lot of smart +pointers' functionality. We explored how it's possible to create a reference +cycle that would cause a memory leak, and how to prevent reference cycles by +using `Weak`. + +If this chapter has piqued your interest and you now want to implement your own +smart pointers, check out [The Nomicon] for even more useful information. + +[The Nomicon]: https://doc.rust-lang.org/stable/nomicon/vec.html Next, let's talk about concurrency in Rust. We'll even learn about a few new smart pointers that can help us with it. From 5af5c4918c583791b0b9ed7dcffd11fdbb3eb4ae Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Sun, 26 Feb 2017 19:49:53 -0500 Subject: [PATCH 10/42] Split into sections --- src/SUMMARY.md | 6 + src/ch15-00-smart-pointers.md | 1257 ---------------------------- src/ch15-01-box.md | 194 +++++ src/ch15-02-deref.md | 175 ++++ src/ch15-03-drop.md | 139 +++ src/ch15-04-rc.md | 203 +++++ src/ch15-05-interior-mutability.md | 235 ++++++ src/ch15-06-reference-cycles.md | 305 +++++++ 8 files changed, 1257 insertions(+), 1257 deletions(-) create mode 100644 src/ch15-01-box.md create mode 100644 src/ch15-02-deref.md create mode 100644 src/ch15-03-drop.md create mode 100644 src/ch15-04-rc.md create mode 100644 src/ch15-05-interior-mutability.md create mode 100644 src/ch15-06-reference-cycles.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index ba2a8a24d..d2a9380b6 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -79,6 +79,12 @@ - [Extending Cargo with Custom Commands](ch14-05-extending-cargo.md) - [Smart Pointers](ch15-00-smart-pointers.md) + - [`Box` Points to Data on the Heap and Has a Known Size](ch15-01-box.md) + - [The `Deref` Trait Allows Access to the Data Through a Reference](ch15-02-deref.md) + - [The `Drop` Trait Runs Code on Cleanup](ch15-03-drop.md) + - [The Reference Counted Smart Pointer `Rc`](ch15-04-rc.md) + - [The Interior Mutability Pattern and `RefCell`](ch15-05-interior-mutability.md) + - [Creating Reference Cycles and Leaking Memory is Safe](ch15-06-reference-cycles.md) - [Concurrency](ch16-00-concurrency.md) diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index 6148f769d..0fe758eab 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -34,1260 +34,3 @@ most common ones from the standard library: `Box`, `Rc`, and * Reference cycles, how they can leak memory, and how to prevent them Let's dive in! - -## `Box` Points to Data on the Heap and Has a Known Size - -The most straightforward smart pointer is a *box*, whose type is more properly -written as `Box`. Boxes allow you to put a single value on the heap, and the -pointer to that value lives on the stack. (We talked about the stack vs. the -heap in Chapter 4.) Listing 15-1 shows how to use a box to store an `i32` on -the heap: - -
-Filename: src/main.rs - -```rust -fn main() { - let b = Box::new(5); - println!("b = {}", b); -} -``` - -
- -Listing 15-1: Storing an `i32` value on the heap using a box - -
-
- -This will print `b = 5`. In this case, we can access the data in the box in a -similar way as we would if this data was on the stack. Just like any value that -has ownership of data, when a box goes out of scope like `b` does at the end of -`main`, it will be deallocated. The deallocation happens for both he box -(stored on the stack) and the data it points to (stored on the heap). - -Putting a single value on the heap isn't very useful, so you won't use boxes by -themselves in the way that Listing 15-1 does very often. A time when boxes are -useful is when you want to ensure that your type has a known size. For -example, consider Listing 15-2, which contains an enum definition for a *cons -list*, a type of data structure that comes from functional programming. - -A cons list is a list where each item contains a value and the next item until -the end of the list, which is signified by a value called `Nil`. Note that we -aren't introducing the idea of "nil" or "null" that we discussed in Chapter 6, -this is just a regular enum variant name we're using because it's the canonical -name to use when describing the cons list data structure. - -
-Filename: src/main.rs - -```rust,ignore -enum List { - Cons(T, List), - Nil, -} -``` - -
- -Listing 15-2: An enum definition for a cons list data structure - -
-
- -Using a cons list to store the list `1, 2, 3` would look like this: - -```rust,ignore -use List::{Cons, Nil}; - -fn main() { - let list = Cons(1, Cons(2, Cons(3, Nil))); -} -``` - -The first `Cons` value holds `1` and another `List` value. This `List` -value is another `Cons` value that holds `2` and another `List` value. This -is one more `Cons` value that holds `3` and a `List` value, which is finally -`Nil`, the non-recursive variant that signals the end of the list. - -However, if we try to compile the above code, we get the error shown in Listing -15-3: - -
- -```text -error[E0072]: recursive type `List` has infinite size - --> - | -1 | enum List { - | _^ starting here... -2 | | Cons(T, List), -3 | | Nil, -4 | | } - | |_^ ...ending here: recursive type has infinite size - | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to - make `List` representable -``` - -
- -Listing 15-3: The error we get when attempting to define a recursive enum - -
-
- -The error says this type 'has infinite size'. Why is that? It's because we've -defined `List` to have a variant that is recursive: it holds another value -of itself. This means Rust can't figure out how much space it needs in order to -store a `List` value. Let's break this down a bit: first let's look at how -Rust decides how much space it needs to store a value of a non-recursive type. -Recall the `Message` enum we defined in Listing 6-2 when we discussed enum -definitions in Chapter 6: - -```rust -enum Message { - Quit, - Move { x: i32, y: i32 }, - Write(String), - ChangeColor(i32, i32, i32), -} -``` - -When Rust needs to know how much space to allocate for a `Message` value, it -can go through each of the variants and see that `Message::Quit` does not need -any space, `Message::Move` needs enough space to store two `i32` values, and so -forth. Therefore, the most space a `Message` value will need is the space it -would take to store the largest of its variants. - -Contrast this to what happens when the Rust compiler looks at a recursive type -like the `List` in Listing 15-2. The compiler tries to figure out how much -memory is needed to store value of `List`, and starts by looking at the -`Cons` variant. The `Cons` variant holds a value of type `T` and a value of -type `List`, so it can use however much the size of `T` is plus the size of -`List`. To figure out how much memory a `List` needs, it looks at its -variants, starting with the `Cons` variant. The `Cons` variant holds a value of -type `T` and a value of type `List`, and this continues infinitely. Rust -can't figure out how much space to allocate for recursively defined types, so -the compiler gives the error in Listing 15-3. - -The compiler did give a helpful suggestion in the error output: - -```text -= help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to - make `List` representable -``` - -Because a `Box` is a pointer, we always know how much space it needs: a -pointer takes up a `usize` amount of space. The value of the `usize` will be -the address of the heap data. The heap data can be any size, but the address to -the start of that heap data will always fit in a `usize`. So if we change our -definition from Listing 15-2 to look like the definition here in Listing 15-4, -and change `main` to use `Box::new` for the values inside the `Cons` variants -like so: - -
-Filename: src/main.rs - -```rust -enum List { - Cons(T, Box>), - Nil, -} - -use List::{Cons, Nil}; - -fn main() { - let list = Cons(1, - Box::new(Cons(2, - Box::new(Cons(3, - Box::new(Nil)))))); -} -``` - -
- -Listing 15-4: Definition of `List` that uses `Box` in order to have a -known size - -
-
- -The compiler will be able to figure out the size it needs to store a `List` -value. Rust will look at `List`, and again start by looking at the `Cons` -variant. The `Cons` variant will need the size of whatever `T` is, plus the -space to store a `usize`, since a box always has the size of a `usize`, no -matter what it's pointing to. Then Rust looks at the `Nil` variant, which does -not store a value, so `Nil` doesn't need any space. We've broken the infinite, -recursive chain by adding in a box. This is the main area where boxes are -useful: breaking up an infinite data structure so that the compiler can know -what size it is. We'll look at another case where Rust has data of unknown size -in Chapter 17 when we discuss trait objects. - -Even though you won't be using boxes very often, they are a good way to -understand the smart pointer pattern. Two of the aspects of `Box` that are -commonly used with smart pointers are its implementations of the `Deref` trait -and the `Drop` trait. Let's investigate how these traits work and how smart -pointers use them. - -## The `Deref` Trait Allows Access to the Data Through a Reference - -The first important smart pointer-related trait is `Deref`, which allows us to -override `*`, the dereference operator (as opposed to the multiplication -operator). Overriding `*` for smart pointers makes accessing the data behind -the smart pointer convenient, and we'll talk about what we mean by convenient -in the next section about deref coercions. Remember using `*` when we talked -about references, like this: - -TODO: put this back in ch 4 - -```rust -let mut x = 5; -{ - let y = &mut x; - - *y += 1 -} - -assert_eq!(6, x); -``` - -We use `*y` to access the data that `y` refers to, rather than `y` itself, -which is a reference. - -END TODO - -Listing 15-5 has an example of overloading `*` using `Deref` on a struct we've -defined to hold mp3 data and metadata. `Mp3` is, in a sense, a smart pointer: -it owns the `Vec` data containing the audio. In addition, it holds some -optional metadata, in this case the artist and title of the song in the audio -data. We want to be able to conveniently access the audio data, not the -metadata, so we implement the `Deref` trait to return the audio data. -Implementing the `Deref` trait requires implementing one method named `deref` -that borrows `self` and returns the inner data: - -
-Filename: src/main.rs - -```rust -use std::ops::Deref; - -struct Mp3 { - audio: Vec, - artist: Option, - title: Option, -} - -impl Deref for Mp3 { - type Target = Vec; - - fn deref(&self) -> &Vec { - &self.audio - } -} - -fn main() { - let my_favorite_song = Mp3 { - // we would read the actual audio data from an mp3 file - audio: vec![1, 2, 3], - artist: Some(String::from("Nirvana")), - title: Some(String::from("Smells Like Teen Spirit")), - }; - - assert_eq!(vec![1, 2, 3], *my_favorite_song); -} -``` - -
- -Listing 15-5: An implementation of the `Deref` trait on a struct that holds mp3 -file data and metadata - -
-
- -Most of this should look familiar: a struct, a trait implementation, and a -main function that creates an instance of the struct. There is one part we -haven't explained thoroughly yet: similarly to Chapter 13 when we looked at the -Iterator trait with the `type Item`, the `type Target = T;` syntax is defining -an associated type, which is covered in more detail in Chapter 20. Don't worry -about that part of the example too much; it is a slightly different way of -declaring a generic parameter. - -In the `assert_eq!`, we're verifying that `vec![1, 2, 3]` is the result we get -when dereferencing the `Mp3` instance with `*my_favorite_song`, which is what -happens since we implemented the `deref` method to return the audio data. If -we hadn't implemented the `Deref` trait for `Mp3`, Rust wouldn't compile the -code `*my_favorite_song`: we'd get an error saying type `Mp3` cannot be -dereferenced. - -The reason this code works is that what the `*` operator is doing behind -the scenes when we call `*my_favorite_song` is: - -```rust,ignore -*(my_favorite_song.deref()) -``` - -This calls the `deref` method on `my_favorite_song`, which borrows -`my_favorite_song` and returns a reference to `my_favorite_song.audio`, since -that's what we defined `deref` to do in Listing 15-5. `*` on references is -defined to just follow the reference and return the data, so the expansion of -`*` doesn't recurse for the outer `*`. So we end up with data of type -`Vec`, which matches the `vec![1, 2, 3]` in the `assert_eq!` in Listing -15-5. - -The reason that the return type of the `deref` method is still a reference and -why it's necessary to dereference the result of the method is that if the -`deref` method returned just the value, using `*` would always take ownership. - -### Implicit Deref Coercions with Functions and Methods - -Rust tends to favor explicitness over implicitness, but one case where this -does not hold true is *deref coercions* of arguments to functions and methods. -A deref coercion will automatically convert references to pointers or smart -pointers, when passed to functions or methods, into references to the pointer's -contents if needed to match the types of the parameters defined in the -signature. Deref coercion was added to Rust to make calling functions and -methods not need as many explicit references and dereferences with `&` and `*`. - -Using our `Mp3` struct from Listing 15-5, here's the signature of a function to -compress mp3 audio data that takes a slice of `u8`: - -```rust,ignore -fn compress_mp3(audio: &[u8]) -> Vec { - // the actual implementation would go here -} -``` - -Because of deref coercion and our implementation of the `Deref` trait on `Mp3`, -we can call this function with the data in `my_favorite_song` by using this -code: - -```rust,ignore -let result = compress_mp3(&my_favorite_song); -``` - -Without deref coercion and our `Deref` implementation on `Mp3`, we would have -to write `compress_mp3(my_favorite_song.audio.as_slice())` in order to call -`compress_mp3` with a slice of the audio data. Deref coercion means that Rust -can use its knowledge of our `Deref` implementation, namely: Rust knows that -`Mp3` implements the `Deref` trait and returns `&Vec` from the `deref` -method. Rust also knows the standard library implements the `Deref` trait on -`Vec` to return `&[T]` from the `deref` method (and we can find that out too -by looking at the API documentation for `Vec`). So, at compile time, Rust -will see that it can use `Deref::deref` twice to turn `&Mp3` into `&Vec` -and then into `&[T]` to match the signature of `compress_mp3`. That means we -get to do less typing! Rust will analyze types through `Deref::deref` as many -times as it needs to in order to get a reference to match the parameter's type, -when the `Deref` trait is defined for the types involved. The indirection is -resolved at compile time, so there is no run-time penalty for taking advantage -of deref coercion. - -There's also a `DerefMut` trait for overriding `*` on `&mut T` for use in -assignment in the same fashion that we use `Deref` to override `*` on `&T`s. - -TODO: insert x/y example here - -Rust does deref coercion when it finds types and trait implementations in three -cases: - -* From `&T` to `&U` when `T: Deref`. -* From `&mut T` to `&mut U` when `T: DerefMut`. -* From `&mut T` to `&U` when `T: Deref`. - -The first two are the same, except for mutability: if you have a `&T`, and -`T` implements `Deref` to some type `U`, you can get a `&U` transparently. Same -for mutable references. The last one is more tricky: if you have a mutable -reference, it will also coerce to an immutable one. The other case is _not_ -possible though: immutable references will never coerce to mutable ones. - -The reason that the `Deref` trait is important to the smart pointer pattern is -that smart pointers can then be treated like regular references and used in -places that expect regular references. We don't have to redefine methods and -functions to take smart pointers explicitly, for example. - -## The `Drop` Trait - -The other trait that's important to the smart pointer pattern is the `Drop` -trait. `Drop` lets us run some code when a value is about to go out of scope. -This is especially useful for smart pointers that manage a resource as opposed -to those that manage memory: often resources like files or network connections -need to be closed when our code is done with them. In other languages, if we -forget to call code to close these kinds of resources, the system our code is -running on might get overloaded and crash. - -In Rust, we can specify that some code should be run when a value goes out of -scope. The compiler will insert this code automatically. That means we don't -need to remember to put this code everywhere we're done with an instance of -these types, but we still won't leak resources! - -The way we specify code should be run when a value goes out of scope is by -implementing the `Drop` trait. The `Drop` trait requires us to implement one -method named `drop` that takes a mutable reference to `self`. - -Listing 15-6 shows a `WebSocket` struct that doesn't actually connect to -anything, but it prints out `Closing the socket!` when we create the struct and -when it goes out of scope so that we can see when this code gets run: - -
-Filename: src/main.rs - -```rust -struct WebSocket { - uri: String, -} - -impl Drop for WebSocket { - fn drop(&mut self) { - println!("Closing the socket!"); - } -} - -fn main() { - let w = WebSocket { uri: String::from("http://example.com/not-real") }; - println!("WebSocket created."); - println!("Wait for it..."); -} -``` - -
- -Listing 15-6: A `WebSocket` struct that implements the `Drop` trait, where we -could put code that would close the socket. - -
-
- -The `Drop` trait is in the prelude, so we don't need to import it. The `drop` -method implementation calls the `println!`; this is where you'd put the actual -code needed to close the socket. In `main`, we create a new instance of -`WebSocket` then print out `WebSocket created.` to be able to see that our code -got to that point at runtime. At the end of `main`, our instance of `WebSocket` -will go out of scope. Note that we didn't call the `drop` method explicitly. - -When we run this program, we'll see: - -```text -WebSocket created. -Wait for it... -Closing the socket! -``` - -printed to the screen, which shows that Rust automatically called `drop` for us -when our instance went out of scope. - -We can use the `std::mem::drop` function to drop a value earlier than when it -goes out of scope. This isn't usually necessary; the whole point of the `Drop` -trait is that it's taken care of automatically for us. We'll see an example of -a case when we'll need to drop a value earlier than when it goes out of scope -in Chapter 16 when we're talking about concurrency. For now, let's just see -that it's possible, and `std::mem::drop` is in the prelude so we can just call -`drop` as shown in Listing 15-7: - -
- -```rust,ignore -fn main() { - let w = WebSocket { uri: String::from("http://example.com/not-real") }; - println!("WebSocket created."); - drop(w); - println!("Wait for it..."); -} -``` - -
- -Listing 15-7: Calling `std::mem::drop` to explicitly drop a value before it -goes out of scope - -
-
- -Running this code will print the following, showing that the destructor code is -called since `Closing the socket!` is printed between `WebSocket created.` and -`Wait for it...`: - -```text -WebSocket created. -Closing the socket! -Wait for it... -``` - -Note that we aren't allowed to call the `drop` method that we defined directly: -if we replaced `drop(w)` in Listing 15-7 with `w.drop()`, we'll get a compiler -error that says `explicit destructor calls not allowed`. TODO: why aren't we -allowed to call the drop method directly? - -The definition of `std::mem::drop` is: - -```rust -pub mod std { - pub mod mem { - pub fn drop(_x: T) { } - } -} -``` - -This function is generic over any type `T`, so we can pass any value to it. The -function doesn't actually have anything in its body, so it doesn't use its -parameter. The parameter is named `_x` because the `_` is a signal to the -compiler that we're intentionally not using the parameter, so it doesn't need -to warn us that we're not using it. The reason this empty function is useful is -that `drop` takes ownership of its parameter, which means the value gets -dropped at the end of this function when it goes out of scope. - -Code specified in a `Drop` trait implementation can be used for many reasons to -make cleanup convenient and safe: we could use it to create our own memory -allocator, for instance! By using the `Drop` trait and Rust's ownership system, -we can't mess up and forget to clean up, or clean up a value that's still in -use. The ownership system makes sure that we call `drop` at the right time. - -Now that we've gone over `Box` and some of the characteristics of smart -pointers, let's talk about a few other smart pointers defined in the standard -library that add different kinds of useful functionality. - -## The Reference Counted Smart Pointer `Rc` - -In the majority of cases, ownership is very clear: you know exactly which -variable owns a given value. However, this isn't always the case; sometimes, -you may actually need multiple owners. For this, Rust has a type called -`Rc`. Its name is an abbreviation for *reference counting*. Reference -counting means keeping track of the number of references to a value in order to -know if a value is still in use or not. If there are zero references to a -value, we know we can clean up the value without any references becoming -invalid. - -To think about this in terms of a real-world scenario, it's like a TV in a -family room. When one person comes in the room to watch TV, they turn it on. -Others can also come in the room and watch the TV. When the last person leaves -the room, they'll turn the TV off since it's no longer being used. If someone -turns off the TV while others are still watching it, though, the people -watching the TV would get mad! - -`Rc` is for use when we want to allocate some read-only data on the heap, -share that data between multiple parts of our program, and we can't determine -at compile time which part of our program using this data will finish using it -last. If we knew which part would finish last, we could make that part the -owner of the data and the normal ownership rules enforced at compile time would -kick in. - -Note that `Rc` is only for use in single-threaded scenarios; the next -chapter on concurrency will cover how to do reference counting in -multithreaded programs. If you try to use `Rc` with multiple threads, -you'll get a compile-time error. - -### Using `Rc` to Share Data - -Let's return to our cons list example from Listing 15-4. In Listing 15-8, we're -going to try to use `List` as we defined it using `Box`. First we'll -create one list instance that contains 5 and then 10. Next, we want to create -two more lists: one that starts with 3 and continues on to our first list -containing 5 and 10, then another list that starts with 4 and *also* continues -on to our first list containing 5 and 10. In other words, we want two lists -that both share ownership of the third list, which conceptually will be -something like this: - -```text -b -> 3 ---v -a ------> 5 -> 10 -> Nil -c -> 4 ---^ -``` - -Trying to implement this using our definition of `List` with `Box` won't -work: - -
-Filename: src/main.rs - -```rust,ignore -enum List { - Cons(T, Box>), - Nil, -} - -use List::{Cons, Nil}; - -fn main() { - let a = Cons(5, - Box::new(Cons(10, - Box::new(Nil)))); - let b = Cons(3, Box::new(a)); - let c = Cons(4, Box::new(a)); -} -``` - -
- -Listing 15-8: Having two lists using `Box` that try to share ownership of a -third list won't work - -
-
- -If we compile this, we get this error: - -```text -error[E0382]: use of moved value: `a` - --> src/main.rs:13:30 - | -12 | let b = Cons(3, Box::new(a)); - | - value moved here -13 | let c = Cons(4, Box::new(a)); - | ^ value used here after move - | - = note: move occurs because `a` has type `List`, which does not - implement the `Copy` trait -``` - -The `Cons` variants own the data they hold, so when we create the `b` list it -moves `a` to be owned by `b`. Then when we try to use `a` again when creating -`c`, we're not allowed to since `a` has been moved. - -We could change the definition of `Cons` to hold references instead, but then -we'd have to specify lifetime parameters and we'd have to construct elements of -a list such that every element lives at least as long as the list itself. -Otherwise, the borrow checker won't even let us compile the code. - -Instead, we can change our definition of `List` to use `Rc` instead of -`Box` as shown here in Listing 15-9: - -
-Filename: src/main.rs - -```rust -enum List { - Cons(T, Rc>), - Nil, -} - -use List::{Cons, Nil}; -use std::rc::Rc; - -fn main() { - let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); - let b = Cons(3, a.clone()); - let c = Cons(4, a.clone()); -} -``` - -
- -Listing 15-9: A definition of `List` that uses `Rc` - -
-
- -Note that we need to add a `use` statement for `Rc` because it's not in the -prelude. In `main`, we create the list holding 5 and 10 and store it in a new -`Rc` in `a`. Then when we create `b` and `c`, we call the `clone` method on `a`. - -### Cloning an `Rc` Increases the Reference Count - -We've seen the `clone` method previously, where we used it for making a -complete copy of some data. With `Rc`, though, it doesn't make a full copy. -`Rc` holds a *reference count*, that is, a count of how many clones exist. -Let's change `main` as shown in Listing 15-10 to have an inner scope around -where we create `c`, and to print out the results of the `Rc::strong_count` -associated function at various points. `Rc::strong_count` returns the reference -count of the `Rc` value we pass to it, and we'll talk about why this function -is named `strong_count` in the section later in this chapter about preventing -reference cycles. - -
-Filename: src/main.rs - -```rust -# enum List { -# Cons(T, Rc>), -# Nil, -# } -# -# use List::{Cons, Nil}; -# use std::rc::Rc; -# -fn main() { - let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); - println!("rc = {}", Rc::strong_count(&a)); - let b = Cons(3, a.clone()); - println!("rc after creating b = {}", Rc::strong_count(&a)); - { - let c = Cons(4, a.clone()); - println!("rc after creating c = {}", Rc::strong_count(&a)); - } - println!("rc after c goes out of scope = {}", Rc::strong_count(&a)); -} -``` - -
- -Listing 15-10: Printing out the reference count - -
-
- -This will print out: - -```text -rc = 1 -rc after creating b = 2 -rc after creating c = 3 -rc after c goes out of scope = 2 -``` - -We're able to see that `a` has an initial reference count of one. Then each -time we call `clone`, the count goes up by one. When `c` goes out of scope, the -count is decreased by one. What we can't see in this example is that when `b` -and then `a` go out of scope at the end of `main`, the count of references to -the list containing 5 and 10 is then 0, and the list is dropped. This strategy -lets us have multiple owners, as the count will ensure that the value remains -valid as long as any of the owners still exist. - -In the beginning of this section, we said that `Rc` is for read-only data, -that is, the value in an `Rc` must be immutable. If it were mutable, we'd run -into a similar problem with borrowing: two mutable borrows to the same place -can cause data races and inconsistencies. But mutating data is very useful! In -the next section, we'll discuss the interior mutability pattern and the -`RefCell` type that we can use in conjunction with an `Rc` to work with -this restriction on immutability. - -## The Interior Mutability Pattern - -*Interior mutability* is a design pattern in Rust for allowing you to mutate -data that's immutable. The interior mutability pattern involves using `unsafe` -code inside a data structure to bend Rust's usual rules around mutation and -borrowing. We haven't yet covered unsafe code, we will in Chapter 20. The -`unsafe` code is then wrapped in a safe API, and the outer type is still -immutable. - -Let's explore this by looking at the `RefCell` type that follows the -interior mutability pattern. - -### `RefCell` has Interior Mutability - -Unlike `Rc`, the `RefCell` type represents single ownership over the data -that it holds. So, what makes `RefCell` different than a type like `Box`? -Let's recall the borrowing rules we learned in Chapter 4: - -1. At any given time, you can have *either* but not both of: - * One mutable reference. - * Any number of immutable references. -2. References must always be valid. - -With references and `Box`, the borrowing rules' invariants are enforced at -compile time. With `RefCell`, these invariants are enforced *at runtime*. -With references, if you break these rules, you'll get a compiler error. With -`RefCell`, if you break these rules, you'll get a `panic!`. - -Static analysis, like the Rust compiler performs, is inherently conservative. -That is, if Rust accepts an incorrect program, people would not be able to -trust in the guarantees Rust makes. If Rust rejects a correct program, the -programmer will be inconvenienced, but nothing catastrophic can occur. -`RefCell` is useful in two situations: - -1. When you know that the borrowing rules are respected, but when the compiler - can't understand that that's true. -2. When you need interior mutability. - -Similarly to `Rc`, `RefCell` is only for use in single-threaded -scenarios. We'll talk about how to get the functionality of `RefCell` in a -multithreaded program in the next chapter on concurrency. For now, all you -need to know is that if you try to use `RefCell` in a multithreaded -context, you'll get a compile time error. - -With references, we use the `&` and `&mut` syntax to create references and -mutable references, respectively. But with `RefCell`, we use the `borrow` -and `borrow_mut` methods, which are part of the safe API that `RefCell` has. - -Listing 15-11 shows what it looks like to use `RefCell` with functions that -borrow their parameters immutably and mutably. Note that the `data` variable is -declared as immutable with `let data` rather than `let mut data`, yet we're -allowed to mutate the value by using `a_fn_that_mutably_borrows`! - -
-Filename: src/main.rs - -```rust -use std::cell::RefCell; - -fn a_fn_that_immutably_borrows(a: &i32) { - println!("a is {}", a); -} - -fn a_fn_that_mutably_borrows(b: &mut i32) { - *b += 1; -} - -fn main() { - let data = RefCell::new(5); - a_fn_that_immutably_borrows(&data.borrow()); - a_fn_that_mutably_borrows(&mut data.borrow_mut()); - a_fn_that_immutably_borrows(&data.borrow()); -} -``` - -
- -Listing 15-11: Using `RefCell`, `borrow`, and `borrow_mut` - -
-
- -This example prints: - -```text -a is 5 -a is 6 -``` - -Here, we've created a new `RefCell` containing the value 5. We can get an -immutable reference to the value inside the `RefCell` by calling the `borrow` -method. More interestingly, we can get a mutable reference to the value inside -the `RefCell` with the `borrow_mut` method, and the function -`a_fn_that_mutably_borrows` is allowed to change the value. We can see that the -next time we print out the value, it's 6 instead of 5. - -Recall that because of the borrowing rules, this code trying to create two -mutable borrows in the same scope won't compile: - -```rust,ignore -let mut s = String::from("hello"); - -let r1 = &mut s; -let r2 = &mut s; -``` - -We'll get this compiler error: - -```text -error[E0499]: cannot borrow `s` as mutable more than once at a time - --> - | -5 | let r1 = &mut s; - | - first mutable borrow occurs here -6 | let r2 = &mut s; - | ^ second mutable borrow occurs here -7 | } - | - first borrow ends here -``` - -In contrast, using `RefCell` and calling `borrow_mut` twice in the same -scope *will* compile, but it will panic at runtime instead. This code: - -```rust,ignore -use std::cell::RefCell; - -fn main() { - let mut s = RefCell::new(String::from("hello")); - - let r1 = s.borrow_mut(); - let r2 = s.borrow_mut(); -} -``` - -compiles but panics with the following error when we `cargo run`: - -```text - Finished dev [unoptimized + debuginfo] target(s) in 0.83 secs - Running `target/debug/refcell` -thread 'main' panicked at 'already borrowed: BorrowMutError', -/stable-dist-rustc/build/src/libcore/result.rs:868 -note: Run with `RUST_BACKTRACE=1` for a backtrace. -``` - -This runtime `BorrowMutError` is similar to the compiler error: it says we've -already borrowed `s` mutably once, so we're not allowed to borrow it again. We -aren't getting around the borrowing rules, we're just choosing to have Rust -enforce them at runtime instead of compile time. You could choose to use -`RefCell` everywhere all the time, but in addition to having to type -`RefCell` a lot, you'd find out about possible problems later (possibly in -production rather than during development). Also, checking the borrowing rules -while your program is running has a performance penalty. - -So why would we choose to make the tradeoffs that using `RefCell` involves? -Well, remember when we said that `Rc` has to store immutable data? Given -that `RefCell` is immutable, but has interior mutability, we can combine -`Rc` and `RefCell` to get a type that's both reference counted and -mutable. Listing 15-12 shows an example of how to do that, again going back to -our cons list from Listing 15-9. In this example, the type we're filling in for -`T` is `Rc>`: - -
-Filename: src/main.rs - -```rust -#[derive(Debug)] -enum List { - Cons(T, Rc>), - Nil, -} - -use List::{Cons, Nil}; -use std::rc::Rc; -use std::cell::RefCell; - -fn main() { - let value = Rc::new(RefCell::new(5)); - - let a = Cons(value.clone(), Rc::new(Nil)); - let shared_list = Rc::new(a); - - let b = Cons(Rc::new(RefCell::new(6)), shared_list.clone()); - let c = Cons(Rc::new(RefCell::new(10)), shared_list.clone()); - - *value.borrow_mut() += 10; - - println!("shared_list after = {:?}", shared_list); - println!("b after = {:?}", b); - println!("c after = {:?}", c); -} -``` - -
- -Listing 15-12: Using `Rc>` to create a `List` that we can mutate - -
-
- -We're creating a value, which is an instance of `T`. We're storing it in a -variable named `value` because we want to be able to access it directly later. -Then we create a `List` in `a` that has a `Cons` variant that holds `value`, -and `value` needs to be cloned since we want `value` to also have ownership in -addition to `a`. Then we wrap `a` in an `Rc` so that we can create lists `b` -and `c` that start differently but both refer to `a`, similarly to what we did -in Listing 15-9. - -Once we have the lists in `shared_list`, `b`, and `c` created, then we add 10 -to the 5 in `value` by dereferencing the `Rc` and calling `borrow_mut` on -the `RefCell`. - -When we print out `shared_list`, `b`, and `c`, we can see that they all have -the modified value of 15: - -```text -shared_list after = Cons(RefCell { value: 15 }, Nil) -b after = Cons(RefCell { value: 6 }, Cons(RefCell { value: 15 }, Nil)) -c after = Cons(RefCell { value: 10 }, Cons(RefCell { value: 15 }, Nil)) -``` - -This is pretty neat! We didn't have to modify our definition of `List` at -all, since the generic parameter lets us substitute any immutable type. By -using `RefCell`, we satisfy the immutable type requirement since -`RefCell` is outwardly immutable, but we can use the methods on `RefCell` -that provide access to its interior mutability to be able to modify our data -when we need to. The runtime checks of the borrowing rules that `RefCell` -does protect us from data races, and we've decided that we want to trade a bit -of speed for the flexibility in our data structures. - -`RefCell` is not the only standard library type that provides interior -mutability. `Cell` is similar but instead of giving references to the inner -value like `RefCell` does, the value is copied in and out of the `Cell`. -`Mutex` offers interior mutability that is safe to use across threads, and -we'll be discussing its use in the next chapter on concurrency. Check out the -standard library docs for more details on the differences between these types. - -## Creating Reference Cycles and Leaking Memory is Safe - -Rust makes a number of guarantees that we've talked about, for example that -we'll never have a null value, and data races will be disallowed at compile -time. Rust's memory safety guarantees make it more difficult to create memory -that never gets cleaned up, which is known as a *memory leak*. Rust does not -make memory leaks *impossible*, however, preventing memory leaks is *not* one -of Rust's guarantees. In other words, memory leaks are memory safe. - -By using `Rc` and `RefCell`, it is possible to create cycles of -references where items refer to each other in a cycle. This is bad because the -reference count of each item in the cycle will never reach 0, and the values -will never be dropped. Let's take a look at how that might happen and how to -prevent it. - -In Listing 15-13, we're going to continue building on the `List` definition -from Listing 15-12. We've added a `RefCell` to the `Cons` variant's definition -so that we can modify a `Cons` instance after we've created it. We've also -added a `next_item` method to make it convenient for us to access the second -item, if we have a `Cons` variant: - -
-Filename: src/main.rs - -```rust -#[derive(Debug)] -enum List { - Cons(T, RefCell>>), - Nil, -} - -impl List { - fn next_item(&self) -> Option<&RefCell>>> { - match *self { - Cons(_, ref item) => Some(item), - Nil => None, - } - } -} -``` - -
- -Listing 15-13: A cons list definition that holds a `RefCell` so that we can -modify what a `Cons` variant is referring to - -
-
- -TODO: insert diagram showing the "shape" of the `Cons` variant? - -Next, in Listing 15-14, we're going to create a `List` value in the variable -`a` that initially is a list of `5, Nil`. Then we'll create a `List` value -in the variable `b` that is a list of the value 10 and then points to the list -in `a`. Finally, we'll modify `a` so that it points to `b` instead of `Nil`, -which will then create a cycle: - -
-Filename: src/main.rs - -```rust -# #[derive(Debug)] -# enum List { -# Cons(T, RefCell>>), -# Nil, -# } -# -# impl List { -# fn next_item(&self) -> Option<&RefCell>>> { -# match *self { -# Cons(_, ref item) => Some(item), -# Nil => None, -# } -# } -# } -# -use List::{Cons, Nil}; -use std::rc::Rc; -use std::cell::RefCell; - -fn main() { - - let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); - - println!("a initial rc count = {}", Rc::strong_count(&a)); - println!("a next item = {:?}", a.next_item()); - - let b = Rc::new(Cons(10, RefCell::new(a.clone()))); - - println!("a rc count after b creation = {}", Rc::strong_count(&a)); - println!("b initial rc count = {}", Rc::strong_count(&b)); - println!("b next item = {:?}", b.next_item()); - - if let Some(ref link) = a.next_item() { - *link.borrow_mut() = b.clone(); - } - - println!("b rc count after changing a = {}", Rc::strong_count(&b)); - println!("a rc count after changing a = {}", Rc::strong_count(&a)); - - // Uncomment the next line to see that we have a cycle; it will - // overflow the stack - // println!("a next item = {:?}", a.next_item()); -} -``` - -
- -Listing 15-14: Creating a reference cycle of two `List` values pointing to -each other - -
-
- -We use the `next_item` method to get a reference to the `RefCell` in `a`, which -we put in the variable `link`. Then we use the `borrow_mut` method on the -`RefCell` to change the value inside from an `Rc` that holds a `Nil` value to -the `Rc` in `b`. We've created a reference cycle that looks like: - -TODO: insert diagram showing b and a pointing to each other - -If you uncomment the last `println!`, Rust will try and print this cycle out -with `a` pointing to `b` pointing to `a` and so forth until it overflows the -stack. - -Looking at the results of the `println!` calls before the last one, we'll see -that the reference count of both `a` and `b` are 2 after we change `a` to point -to `b`. At the end of `main`, Rust will try and drop `b` first, which will -decrease the count of the `Rc` by one. However, because `a` is still -referencing that `Rc`, its count is 1 rather than 0, so the memory the `Rc` has -on the heap won't be dropped. It'll just sit there with a count of one, -forever. In this specific case, the program ends right away, so it's not a -problem, but in a more complex program that allocates lots of memory in a cycle -and holds onto it for a long time, this would be a problem. The program would -be using more memory than it needs to be, and might overwhelm the system and -cause it to run out of memory available to use. - -Now, as you can see, creating reference cycles is difficult and inconvenient in -Rust. To be honest, your authors had to look up previous discussions of an -example to get this right. But it's not impossible: preventing memory leaks in -the form of reference cycles is not one of the guarantees Rust makes. If you -have `RefCell` values that contain `Rc` values or similar nested -combinations of types with interior mutability and reference counting, be aware -that you'll have to ensure that you don't create cycles on your. One way of -doing that is using `Weak`. - -### Prevent Reference Cycles: Turn an `Rc` into a `Weak` - -To help with this problem, the Rust standard library contains another smart -pointer type: `Weak`. We've been showing how cloning an `Rc` increases -the `strong_count` of references; `Weak` is a way to reference an `Rc` -that does not increment the `strong_count`: instead it increments the -`weak_count` of references to an `Rc`. When an `Rc` goes out of scope, the -inner value will get dropped if the `strong_count` is 0, even if the -`weak_count` is not 0. When we attempt to use a `Weak` reference, we'll get -an `Option` that will be `Some` if the `Rc` value has not been dropped yet, -and `None` if the `Rc` value has been dropped. - -So in order to make it possible to create lists that point to each other but not create reference cycles, in Listing 15-15, we're going to change our definition of `List` again to hold a `Weak` instead of an `Rc`. - -
-Filename: src/main.rs - -```rust -#[derive(Debug)] -enum List { - Cons(T, RefCell>>), - Nil, -} - -impl List { - fn next_item(&self) -> Option>> { - match *self { - Cons(_, ref n) => (&*n.borrow()).upgrade(), - Nil => None, - } - } -} -``` - -
- -Listing 15-15: Modifying `List` to have `Weak` references instead of -`Rc` - -
-
- -We've also modified the `next_item` method: not only does it return `None` when -`self` is `Nil` and doesn't have a `next_item`, it now also returns `None` if -the value that the `Weak` references has been dropped. The `upgrade` method -on a `Weak` value returns `Some` containing an `Rc` if the value has not yet -been dropped and `None` if the value has been dropped. - -TODO: is this bad software design, collapsing two cases that return `None` like this??? - -To create `Weak` values, we call the `Rc::downgrade` associated function, -which takes an `&Rc` as an argument, and gives a `Weak` back. - -Listing 15-16 shows a `main` method where we're trying to create `a` and `b` lists that point to each other, similarly to what we did in Listing 15-14, but this time we won't have a reference cycle and the values will be dropped when they go out of scope at the end of `main`: - -
- -```rust -# #[derive(Debug)] -# enum List { -# Cons(T, RefCell>>), -# Nil, -# } -# -# impl List { -# fn next_item(&self) -> Option>> { -# match *self { -# Cons(_, ref n) => (&*n.borrow()).upgrade(), -# Nil => None, -# } -# } -# } -# -use List::{Cons, Nil}; -use std::rc::{Rc, Weak}; -use std::cell::RefCell; - -fn main() { - let nil = Rc::new(Nil); - - let a = Rc::new(Cons(5, RefCell::new(Rc::downgrade(&nil)))); - - println!("a.next_item() = {:?}", a.next_item()); - - { - let b = Rc::new(Cons(10, RefCell::new(Rc::downgrade(&a.clone())))); - - if let Cons(_, ref link) = *a { - *link.borrow_mut() = Rc::downgrade(&b.clone()); - } - - println!("a.next_item() = {:?}", a.next_item()); - println!("b.next_item() = {:?}", b.next_item()); - } - - println!("a.next_item() = {:?}", a.next_item()); -} -``` - -
- -Listing 15-16: Creating `List` values using weak references - -
-
- -First, we create a variable for the `Rc` that holds the `Nil` value, so that -it's clearer to see that we call `Rc::downgrade` and pass a reference to `nil` -when we create `a`. At that point, we print out the value of `a.next_item()` -and we can see that it's `Some(Nil)`. - -We've added an inner scope in order to demonstrate what happens when `b` goes -out of scope. In the inner scope, we create `b` that has a weak reference to -`a`, and then we modify `a` to have a weak reference to `b` instead of to -`nil`. At the end of the inner scope, we can see that `a` and `b` are pointing -to each other, but through weak references. - -At the end of the inner scope, `b` goes out of scope. The value that the -`Rc` in `b` holds gets dropped, even though `a` still references it, because -the reference in `a` is a weak reference that doesn't count when Rust decides -whether the value in `b` should be dropped or not. At the end of `main` when we -print out `a.next_item()` again, we can see that we now get a `None` value -since the value that the weak reference in `a` was pointing to has been -dropped. Success! We've broken the cycle. - -Add some `println!` statements at various places that display the values that -`Rc::strong_count` and `Rc::weak_count` return for `a` and `b` at different -points in this example to see which parts of the code increase or decrease the -strong or weak counts. - -If you're doing complex things with `Rc`s, you should investigate if it's -possible for you to have a cycle, and insert a `Weak` so that you don't -create cycles and leak memory. The specifics depend on exactly what you're -doing, but luckily, this isn't a Rust-specific idea; all of this translates -over to other reference counting libraries in other languages, so doing some -reading about it should help you. - -## Summary - -We've now covered how you can use different kinds of smart pointers to choose -different guarantees and tradeoffs than those Rust makes with regular -references. `Box` has a known size and points to data allocated on the heap. -`Rc` keeps track of the number of references to data on the heap so that -data can have multiple owners. `RefCell` with its interior mutability gives -us a type that can be used where we need an immutable type, and enforces the -borrowing rules at runtime instead of at compile time. - -We've also discussed the `Deref` and `Drop` traits that enable a lot of smart -pointers' functionality. We explored how it's possible to create a reference -cycle that would cause a memory leak, and how to prevent reference cycles by -using `Weak`. - -If this chapter has piqued your interest and you now want to implement your own -smart pointers, check out [The Nomicon] for even more useful information. - -[The Nomicon]: https://doc.rust-lang.org/stable/nomicon/vec.html - -Next, let's talk about concurrency in Rust. We'll even learn about a few new -smart pointers that can help us with it. diff --git a/src/ch15-01-box.md b/src/ch15-01-box.md new file mode 100644 index 000000000..62cb39e2a --- /dev/null +++ b/src/ch15-01-box.md @@ -0,0 +1,194 @@ +## `Box` Points to Data on the Heap and Has a Known Size + +The most straightforward smart pointer is a *box*, whose type is more properly +written as `Box`. Boxes allow you to put a single value on the heap, and the +pointer to that value lives on the stack. (We talked about the stack vs. the +heap in Chapter 4.) Listing 15-1 shows how to use a box to store an `i32` on +the heap: + +
+Filename: src/main.rs + +```rust +fn main() { + let b = Box::new(5); + println!("b = {}", b); +} +``` + +
+ +Listing 15-1: Storing an `i32` value on the heap using a box + +
+
+ +This will print `b = 5`. In this case, we can access the data in the box in a +similar way as we would if this data was on the stack. Just like any value that +has ownership of data, when a box goes out of scope like `b` does at the end of +`main`, it will be deallocated. The deallocation happens for both he box +(stored on the stack) and the data it points to (stored on the heap). + +Putting a single value on the heap isn't very useful, so you won't use boxes by +themselves in the way that Listing 15-1 does very often. A time when boxes are +useful is when you want to ensure that your type has a known size. For +example, consider Listing 15-2, which contains an enum definition for a *cons +list*, a type of data structure that comes from functional programming. + +A cons list is a list where each item contains a value and the next item until +the end of the list, which is signified by a value called `Nil`. Note that we +aren't introducing the idea of "nil" or "null" that we discussed in Chapter 6, +this is just a regular enum variant name we're using because it's the canonical +name to use when describing the cons list data structure. + +
+Filename: src/main.rs + +```rust,ignore +enum List { + Cons(T, List), + Nil, +} +``` + +
+ +Listing 15-2: An enum definition for a cons list data structure + +
+
+ +Using a cons list to store the list `1, 2, 3` would look like this: + +```rust,ignore +use List::{Cons, Nil}; + +fn main() { + let list = Cons(1, Cons(2, Cons(3, Nil))); +} +``` + +The first `Cons` value holds `1` and another `List` value. This `List` +value is another `Cons` value that holds `2` and another `List` value. This +is one more `Cons` value that holds `3` and a `List` value, which is finally +`Nil`, the non-recursive variant that signals the end of the list. + +However, if we try to compile the above code, we get the error shown in Listing +15-3: + +
+ +```text +error[E0072]: recursive type `List` has infinite size + --> + | +1 | enum List { + | _^ starting here... +2 | | Cons(T, List), +3 | | Nil, +4 | | } + | |_^ ...ending here: recursive type has infinite size + | + = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to + make `List` representable +``` + +
+ +Listing 15-3: The error we get when attempting to define a recursive enum + +
+
+ +The error says this type 'has infinite size'. Why is that? It's because we've +defined `List` to have a variant that is recursive: it holds another value +of itself. This means Rust can't figure out how much space it needs in order to +store a `List` value. Let's break this down a bit: first let's look at how +Rust decides how much space it needs to store a value of a non-recursive type. +Recall the `Message` enum we defined in Listing 6-2 when we discussed enum +definitions in Chapter 6: + +```rust +enum Message { + Quit, + Move { x: i32, y: i32 }, + Write(String), + ChangeColor(i32, i32, i32), +} +``` + +When Rust needs to know how much space to allocate for a `Message` value, it +can go through each of the variants and see that `Message::Quit` does not need +any space, `Message::Move` needs enough space to store two `i32` values, and so +forth. Therefore, the most space a `Message` value will need is the space it +would take to store the largest of its variants. + +Contrast this to what happens when the Rust compiler looks at a recursive type +like the `List` in Listing 15-2. The compiler tries to figure out how much +memory is needed to store value of `List`, and starts by looking at the +`Cons` variant. The `Cons` variant holds a value of type `T` and a value of +type `List`, so it can use however much the size of `T` is plus the size of +`List`. To figure out how much memory a `List` needs, it looks at its +variants, starting with the `Cons` variant. The `Cons` variant holds a value of +type `T` and a value of type `List`, and this continues infinitely. Rust +can't figure out how much space to allocate for recursively defined types, so +the compiler gives the error in Listing 15-3. + +The compiler did give a helpful suggestion in the error output: + +```text += help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to + make `List` representable +``` + +Because a `Box` is a pointer, we always know how much space it needs: a +pointer takes up a `usize` amount of space. The value of the `usize` will be +the address of the heap data. The heap data can be any size, but the address to +the start of that heap data will always fit in a `usize`. So if we change our +definition from Listing 15-2 to look like the definition here in Listing 15-4, +and change `main` to use `Box::new` for the values inside the `Cons` variants +like so: + +
+Filename: src/main.rs + +```rust +enum List { + Cons(T, Box>), + Nil, +} + +use List::{Cons, Nil}; + +fn main() { + let list = Cons(1, + Box::new(Cons(2, + Box::new(Cons(3, + Box::new(Nil)))))); +} +``` + +
+ +Listing 15-4: Definition of `List` that uses `Box` in order to have a +known size + +
+
+ +The compiler will be able to figure out the size it needs to store a `List` +value. Rust will look at `List`, and again start by looking at the `Cons` +variant. The `Cons` variant will need the size of whatever `T` is, plus the +space to store a `usize`, since a box always has the size of a `usize`, no +matter what it's pointing to. Then Rust looks at the `Nil` variant, which does +not store a value, so `Nil` doesn't need any space. We've broken the infinite, +recursive chain by adding in a box. This is the main area where boxes are +useful: breaking up an infinite data structure so that the compiler can know +what size it is. We'll look at another case where Rust has data of unknown size +in Chapter 17 when we discuss trait objects. + +Even though you won't be using boxes very often, they are a good way to +understand the smart pointer pattern. Two of the aspects of `Box` that are +commonly used with smart pointers are its implementations of the `Deref` trait +and the `Drop` trait. Let's investigate how these traits work and how smart +pointers use them. diff --git a/src/ch15-02-deref.md b/src/ch15-02-deref.md new file mode 100644 index 000000000..24b431735 --- /dev/null +++ b/src/ch15-02-deref.md @@ -0,0 +1,175 @@ +## The `Deref` Trait Allows Access to the Data Through a Reference + +The first important smart pointer-related trait is `Deref`, which allows us to +override `*`, the dereference operator (as opposed to the multiplication +operator). Overriding `*` for smart pointers makes accessing the data behind +the smart pointer convenient, and we'll talk about what we mean by convenient +in the next section about deref coercions. Remember using `*` when we talked +about references, like this: + +TODO: put this back in ch 4 + +```rust +let mut x = 5; +{ + let y = &mut x; + + *y += 1 +} + +assert_eq!(6, x); +``` + +We use `*y` to access the data that `y` refers to, rather than `y` itself, +which is a reference. + +END TODO + +Listing 15-5 has an example of overloading `*` using `Deref` on a struct we've +defined to hold mp3 data and metadata. `Mp3` is, in a sense, a smart pointer: +it owns the `Vec` data containing the audio. In addition, it holds some +optional metadata, in this case the artist and title of the song in the audio +data. We want to be able to conveniently access the audio data, not the +metadata, so we implement the `Deref` trait to return the audio data. +Implementing the `Deref` trait requires implementing one method named `deref` +that borrows `self` and returns the inner data: + +
+Filename: src/main.rs + +```rust +use std::ops::Deref; + +struct Mp3 { + audio: Vec, + artist: Option, + title: Option, +} + +impl Deref for Mp3 { + type Target = Vec; + + fn deref(&self) -> &Vec { + &self.audio + } +} + +fn main() { + let my_favorite_song = Mp3 { + // we would read the actual audio data from an mp3 file + audio: vec![1, 2, 3], + artist: Some(String::from("Nirvana")), + title: Some(String::from("Smells Like Teen Spirit")), + }; + + assert_eq!(vec![1, 2, 3], *my_favorite_song); +} +``` + +
+ +Listing 15-5: An implementation of the `Deref` trait on a struct that holds mp3 +file data and metadata + +
+
+ +Most of this should look familiar: a struct, a trait implementation, and a +main function that creates an instance of the struct. There is one part we +haven't explained thoroughly yet: similarly to Chapter 13 when we looked at the +Iterator trait with the `type Item`, the `type Target = T;` syntax is defining +an associated type, which is covered in more detail in Chapter 20. Don't worry +about that part of the example too much; it is a slightly different way of +declaring a generic parameter. + +In the `assert_eq!`, we're verifying that `vec![1, 2, 3]` is the result we get +when dereferencing the `Mp3` instance with `*my_favorite_song`, which is what +happens since we implemented the `deref` method to return the audio data. If +we hadn't implemented the `Deref` trait for `Mp3`, Rust wouldn't compile the +code `*my_favorite_song`: we'd get an error saying type `Mp3` cannot be +dereferenced. + +The reason this code works is that what the `*` operator is doing behind +the scenes when we call `*my_favorite_song` is: + +```rust,ignore +*(my_favorite_song.deref()) +``` + +This calls the `deref` method on `my_favorite_song`, which borrows +`my_favorite_song` and returns a reference to `my_favorite_song.audio`, since +that's what we defined `deref` to do in Listing 15-5. `*` on references is +defined to just follow the reference and return the data, so the expansion of +`*` doesn't recurse for the outer `*`. So we end up with data of type +`Vec`, which matches the `vec![1, 2, 3]` in the `assert_eq!` in Listing +15-5. + +The reason that the return type of the `deref` method is still a reference and +why it's necessary to dereference the result of the method is that if the +`deref` method returned just the value, using `*` would always take ownership. + +### Implicit Deref Coercions with Functions and Methods + +Rust tends to favor explicitness over implicitness, but one case where this +does not hold true is *deref coercions* of arguments to functions and methods. +A deref coercion will automatically convert references to pointers or smart +pointers, when passed to functions or methods, into references to the pointer's +contents if needed to match the types of the parameters defined in the +signature. Deref coercion was added to Rust to make calling functions and +methods not need as many explicit references and dereferences with `&` and `*`. + +Using our `Mp3` struct from Listing 15-5, here's the signature of a function to +compress mp3 audio data that takes a slice of `u8`: + +```rust,ignore +fn compress_mp3(audio: &[u8]) -> Vec { + // the actual implementation would go here +} +``` + +Because of deref coercion and our implementation of the `Deref` trait on `Mp3`, +we can call this function with the data in `my_favorite_song` by using this +code: + +```rust,ignore +let result = compress_mp3(&my_favorite_song); +``` + +Without deref coercion and our `Deref` implementation on `Mp3`, we would have +to write `compress_mp3(my_favorite_song.audio.as_slice())` in order to call +`compress_mp3` with a slice of the audio data. Deref coercion means that Rust +can use its knowledge of our `Deref` implementation, namely: Rust knows that +`Mp3` implements the `Deref` trait and returns `&Vec` from the `deref` +method. Rust also knows the standard library implements the `Deref` trait on +`Vec` to return `&[T]` from the `deref` method (and we can find that out too +by looking at the API documentation for `Vec`). So, at compile time, Rust +will see that it can use `Deref::deref` twice to turn `&Mp3` into `&Vec` +and then into `&[T]` to match the signature of `compress_mp3`. That means we +get to do less typing! Rust will analyze types through `Deref::deref` as many +times as it needs to in order to get a reference to match the parameter's type, +when the `Deref` trait is defined for the types involved. The indirection is +resolved at compile time, so there is no run-time penalty for taking advantage +of deref coercion. + +There's also a `DerefMut` trait for overriding `*` on `&mut T` for use in +assignment in the same fashion that we use `Deref` to override `*` on `&T`s. + +TODO: insert x/y example here + +Rust does deref coercion when it finds types and trait implementations in three +cases: + +* From `&T` to `&U` when `T: Deref`. +* From `&mut T` to `&mut U` when `T: DerefMut`. +* From `&mut T` to `&U` when `T: Deref`. + +The first two are the same, except for mutability: if you have a `&T`, and +`T` implements `Deref` to some type `U`, you can get a `&U` transparently. Same +for mutable references. The last one is more tricky: if you have a mutable +reference, it will also coerce to an immutable one. The other case is _not_ +possible though: immutable references will never coerce to mutable ones. + +The reason that the `Deref` trait is important to the smart pointer pattern is +that smart pointers can then be treated like regular references and used in +places that expect regular references. We don't have to redefine methods and +functions to take smart pointers explicitly, for example. diff --git a/src/ch15-03-drop.md b/src/ch15-03-drop.md new file mode 100644 index 000000000..b0b0c988a --- /dev/null +++ b/src/ch15-03-drop.md @@ -0,0 +1,139 @@ +## The `Drop` Trait Runs Code on Cleanup + +The other trait that's important to the smart pointer pattern is the `Drop` +trait. `Drop` lets us run some code when a value is about to go out of scope. +This is especially useful for smart pointers that manage a resource as opposed +to those that manage memory: often resources like files or network connections +need to be closed when our code is done with them. In other languages, if we +forget to call code to close these kinds of resources, the system our code is +running on might get overloaded and crash. + +In Rust, we can specify that some code should be run when a value goes out of +scope. The compiler will insert this code automatically. That means we don't +need to remember to put this code everywhere we're done with an instance of +these types, but we still won't leak resources! + +The way we specify code should be run when a value goes out of scope is by +implementing the `Drop` trait. The `Drop` trait requires us to implement one +method named `drop` that takes a mutable reference to `self`. + +Listing 15-6 shows a `WebSocket` struct that doesn't actually connect to +anything, but it prints out `Closing the socket!` when we create the struct and +when it goes out of scope so that we can see when this code gets run: + +
+Filename: src/main.rs + +```rust +struct WebSocket { + uri: String, +} + +impl Drop for WebSocket { + fn drop(&mut self) { + println!("Closing the socket!"); + } +} + +fn main() { + let w = WebSocket { uri: String::from("http://example.com/not-real") }; + println!("WebSocket created."); + println!("Wait for it..."); +} +``` + +
+ +Listing 15-6: A `WebSocket` struct that implements the `Drop` trait, where we +could put code that would close the socket. + +
+
+ +The `Drop` trait is in the prelude, so we don't need to import it. The `drop` +method implementation calls the `println!`; this is where you'd put the actual +code needed to close the socket. In `main`, we create a new instance of +`WebSocket` then print out `WebSocket created.` to be able to see that our code +got to that point at runtime. At the end of `main`, our instance of `WebSocket` +will go out of scope. Note that we didn't call the `drop` method explicitly. + +When we run this program, we'll see: + +```text +WebSocket created. +Wait for it... +Closing the socket! +``` + +printed to the screen, which shows that Rust automatically called `drop` for us +when our instance went out of scope. + +We can use the `std::mem::drop` function to drop a value earlier than when it +goes out of scope. This isn't usually necessary; the whole point of the `Drop` +trait is that it's taken care of automatically for us. We'll see an example of +a case when we'll need to drop a value earlier than when it goes out of scope +in Chapter 16 when we're talking about concurrency. For now, let's just see +that it's possible, and `std::mem::drop` is in the prelude so we can just call +`drop` as shown in Listing 15-7: + +
+ +```rust,ignore +fn main() { + let w = WebSocket { uri: String::from("http://example.com/not-real") }; + println!("WebSocket created."); + drop(w); + println!("Wait for it..."); +} +``` + +
+ +Listing 15-7: Calling `std::mem::drop` to explicitly drop a value before it +goes out of scope + +
+
+ +Running this code will print the following, showing that the destructor code is +called since `Closing the socket!` is printed between `WebSocket created.` and +`Wait for it...`: + +```text +WebSocket created. +Closing the socket! +Wait for it... +``` + +Note that we aren't allowed to call the `drop` method that we defined directly: +if we replaced `drop(w)` in Listing 15-7 with `w.drop()`, we'll get a compiler +error that says `explicit destructor calls not allowed`. TODO: why aren't we +allowed to call the drop method directly? + +The definition of `std::mem::drop` is: + +```rust +pub mod std { + pub mod mem { + pub fn drop(_x: T) { } + } +} +``` + +This function is generic over any type `T`, so we can pass any value to it. The +function doesn't actually have anything in its body, so it doesn't use its +parameter. The parameter is named `_x` because the `_` is a signal to the +compiler that we're intentionally not using the parameter, so it doesn't need +to warn us that we're not using it. The reason this empty function is useful is +that `drop` takes ownership of its parameter, which means the value gets +dropped at the end of this function when it goes out of scope. + +Code specified in a `Drop` trait implementation can be used for many reasons to +make cleanup convenient and safe: we could use it to create our own memory +allocator, for instance! By using the `Drop` trait and Rust's ownership system, +we can't mess up and forget to clean up, or clean up a value that's still in +use. The ownership system makes sure that we call `drop` at the right time. + +Now that we've gone over `Box` and some of the characteristics of smart +pointers, let's talk about a few other smart pointers defined in the standard +library that add different kinds of useful functionality. diff --git a/src/ch15-04-rc.md b/src/ch15-04-rc.md new file mode 100644 index 000000000..be1cb5716 --- /dev/null +++ b/src/ch15-04-rc.md @@ -0,0 +1,203 @@ +## The Reference Counted Smart Pointer `Rc` + +In the majority of cases, ownership is very clear: you know exactly which +variable owns a given value. However, this isn't always the case; sometimes, +you may actually need multiple owners. For this, Rust has a type called +`Rc`. Its name is an abbreviation for *reference counting*. Reference +counting means keeping track of the number of references to a value in order to +know if a value is still in use or not. If there are zero references to a +value, we know we can clean up the value without any references becoming +invalid. + +To think about this in terms of a real-world scenario, it's like a TV in a +family room. When one person comes in the room to watch TV, they turn it on. +Others can also come in the room and watch the TV. When the last person leaves +the room, they'll turn the TV off since it's no longer being used. If someone +turns off the TV while others are still watching it, though, the people +watching the TV would get mad! + +`Rc` is for use when we want to allocate some read-only data on the heap, +share that data between multiple parts of our program, and we can't determine +at compile time which part of our program using this data will finish using it +last. If we knew which part would finish last, we could make that part the +owner of the data and the normal ownership rules enforced at compile time would +kick in. + +Note that `Rc` is only for use in single-threaded scenarios; the next +chapter on concurrency will cover how to do reference counting in +multithreaded programs. If you try to use `Rc` with multiple threads, +you'll get a compile-time error. + +### Using `Rc` to Share Data + +Let's return to our cons list example from Listing 15-4. In Listing 15-8, we're +going to try to use `List` as we defined it using `Box`. First we'll +create one list instance that contains 5 and then 10. Next, we want to create +two more lists: one that starts with 3 and continues on to our first list +containing 5 and 10, then another list that starts with 4 and *also* continues +on to our first list containing 5 and 10. In other words, we want two lists +that both share ownership of the third list, which conceptually will be +something like this: + +```text +b -> 3 ---v +a ------> 5 -> 10 -> Nil +c -> 4 ---^ +``` + +Trying to implement this using our definition of `List` with `Box` won't +work: + +
+Filename: src/main.rs + +```rust,ignore +enum List { + Cons(T, Box>), + Nil, +} + +use List::{Cons, Nil}; + +fn main() { + let a = Cons(5, + Box::new(Cons(10, + Box::new(Nil)))); + let b = Cons(3, Box::new(a)); + let c = Cons(4, Box::new(a)); +} +``` + +
+ +Listing 15-8: Having two lists using `Box` that try to share ownership of a +third list won't work + +
+
+ +If we compile this, we get this error: + +```text +error[E0382]: use of moved value: `a` + --> src/main.rs:13:30 + | +12 | let b = Cons(3, Box::new(a)); + | - value moved here +13 | let c = Cons(4, Box::new(a)); + | ^ value used here after move + | + = note: move occurs because `a` has type `List`, which does not + implement the `Copy` trait +``` + +The `Cons` variants own the data they hold, so when we create the `b` list it +moves `a` to be owned by `b`. Then when we try to use `a` again when creating +`c`, we're not allowed to since `a` has been moved. + +We could change the definition of `Cons` to hold references instead, but then +we'd have to specify lifetime parameters and we'd have to construct elements of +a list such that every element lives at least as long as the list itself. +Otherwise, the borrow checker won't even let us compile the code. + +Instead, we can change our definition of `List` to use `Rc` instead of +`Box` as shown here in Listing 15-9: + +
+Filename: src/main.rs + +```rust +enum List { + Cons(T, Rc>), + Nil, +} + +use List::{Cons, Nil}; +use std::rc::Rc; + +fn main() { + let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); + let b = Cons(3, a.clone()); + let c = Cons(4, a.clone()); +} +``` + +
+ +Listing 15-9: A definition of `List` that uses `Rc` + +
+
+ +Note that we need to add a `use` statement for `Rc` because it's not in the +prelude. In `main`, we create the list holding 5 and 10 and store it in a new +`Rc` in `a`. Then when we create `b` and `c`, we call the `clone` method on `a`. + +### Cloning an `Rc` Increases the Reference Count + +We've seen the `clone` method previously, where we used it for making a +complete copy of some data. With `Rc`, though, it doesn't make a full copy. +`Rc` holds a *reference count*, that is, a count of how many clones exist. +Let's change `main` as shown in Listing 15-10 to have an inner scope around +where we create `c`, and to print out the results of the `Rc::strong_count` +associated function at various points. `Rc::strong_count` returns the reference +count of the `Rc` value we pass to it, and we'll talk about why this function +is named `strong_count` in the section later in this chapter about preventing +reference cycles. + +
+Filename: src/main.rs + +```rust +# enum List { +# Cons(T, Rc>), +# Nil, +# } +# +# use List::{Cons, Nil}; +# use std::rc::Rc; +# +fn main() { + let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); + println!("rc = {}", Rc::strong_count(&a)); + let b = Cons(3, a.clone()); + println!("rc after creating b = {}", Rc::strong_count(&a)); + { + let c = Cons(4, a.clone()); + println!("rc after creating c = {}", Rc::strong_count(&a)); + } + println!("rc after c goes out of scope = {}", Rc::strong_count(&a)); +} +``` + +
+ +Listing 15-10: Printing out the reference count + +
+
+ +This will print out: + +```text +rc = 1 +rc after creating b = 2 +rc after creating c = 3 +rc after c goes out of scope = 2 +``` + +We're able to see that `a` has an initial reference count of one. Then each +time we call `clone`, the count goes up by one. When `c` goes out of scope, the +count is decreased by one. What we can't see in this example is that when `b` +and then `a` go out of scope at the end of `main`, the count of references to +the list containing 5 and 10 is then 0, and the list is dropped. This strategy +lets us have multiple owners, as the count will ensure that the value remains +valid as long as any of the owners still exist. + +In the beginning of this section, we said that `Rc` is for read-only data, +that is, the value in an `Rc` must be immutable. If it were mutable, we'd run +into a similar problem with borrowing: two mutable borrows to the same place +can cause data races and inconsistencies. But mutating data is very useful! In +the next section, we'll discuss the interior mutability pattern and the +`RefCell` type that we can use in conjunction with an `Rc` to work with +this restriction on immutability. diff --git a/src/ch15-05-interior-mutability.md b/src/ch15-05-interior-mutability.md new file mode 100644 index 000000000..86407c679 --- /dev/null +++ b/src/ch15-05-interior-mutability.md @@ -0,0 +1,235 @@ +## The Interior Mutability Pattern and `RefCell` + +*Interior mutability* is a design pattern in Rust for allowing you to mutate +data that's immutable. The interior mutability pattern involves using `unsafe` +code inside a data structure to bend Rust's usual rules around mutation and +borrowing. We haven't yet covered unsafe code, we will in Chapter 20. The +`unsafe` code is then wrapped in a safe API, and the outer type is still +immutable. + +Let's explore this by looking at the `RefCell` type that follows the +interior mutability pattern. + +### `RefCell` has Interior Mutability + +Unlike `Rc`, the `RefCell` type represents single ownership over the data +that it holds. So, what makes `RefCell` different than a type like `Box`? +Let's recall the borrowing rules we learned in Chapter 4: + +1. At any given time, you can have *either* but not both of: + * One mutable reference. + * Any number of immutable references. +2. References must always be valid. + +With references and `Box`, the borrowing rules' invariants are enforced at +compile time. With `RefCell`, these invariants are enforced *at runtime*. +With references, if you break these rules, you'll get a compiler error. With +`RefCell`, if you break these rules, you'll get a `panic!`. + +Static analysis, like the Rust compiler performs, is inherently conservative. +That is, if Rust accepts an incorrect program, people would not be able to +trust in the guarantees Rust makes. If Rust rejects a correct program, the +programmer will be inconvenienced, but nothing catastrophic can occur. +`RefCell` is useful in two situations: + +1. When you know that the borrowing rules are respected, but when the compiler + can't understand that that's true. +2. When you need interior mutability. + +Similarly to `Rc`, `RefCell` is only for use in single-threaded +scenarios. We'll talk about how to get the functionality of `RefCell` in a +multithreaded program in the next chapter on concurrency. For now, all you +need to know is that if you try to use `RefCell` in a multithreaded +context, you'll get a compile time error. + +With references, we use the `&` and `&mut` syntax to create references and +mutable references, respectively. But with `RefCell`, we use the `borrow` +and `borrow_mut` methods, which are part of the safe API that `RefCell` has. + +Listing 15-11 shows what it looks like to use `RefCell` with functions that +borrow their parameters immutably and mutably. Note that the `data` variable is +declared as immutable with `let data` rather than `let mut data`, yet we're +allowed to mutate the value by using `a_fn_that_mutably_borrows`! + +
+Filename: src/main.rs + +```rust +use std::cell::RefCell; + +fn a_fn_that_immutably_borrows(a: &i32) { + println!("a is {}", a); +} + +fn a_fn_that_mutably_borrows(b: &mut i32) { + *b += 1; +} + +fn main() { + let data = RefCell::new(5); + a_fn_that_immutably_borrows(&data.borrow()); + a_fn_that_mutably_borrows(&mut data.borrow_mut()); + a_fn_that_immutably_borrows(&data.borrow()); +} +``` + +
+ +Listing 15-11: Using `RefCell`, `borrow`, and `borrow_mut` + +
+
+ +This example prints: + +```text +a is 5 +a is 6 +``` + +Here, we've created a new `RefCell` containing the value 5. We can get an +immutable reference to the value inside the `RefCell` by calling the `borrow` +method. More interestingly, we can get a mutable reference to the value inside +the `RefCell` with the `borrow_mut` method, and the function +`a_fn_that_mutably_borrows` is allowed to change the value. We can see that the +next time we print out the value, it's 6 instead of 5. + +Recall that because of the borrowing rules, this code trying to create two +mutable borrows in the same scope won't compile: + +```rust,ignore +let mut s = String::from("hello"); + +let r1 = &mut s; +let r2 = &mut s; +``` + +We'll get this compiler error: + +```text +error[E0499]: cannot borrow `s` as mutable more than once at a time + --> + | +5 | let r1 = &mut s; + | - first mutable borrow occurs here +6 | let r2 = &mut s; + | ^ second mutable borrow occurs here +7 | } + | - first borrow ends here +``` + +In contrast, using `RefCell` and calling `borrow_mut` twice in the same +scope *will* compile, but it will panic at runtime instead. This code: + +```rust,ignore +use std::cell::RefCell; + +fn main() { + let mut s = RefCell::new(String::from("hello")); + + let r1 = s.borrow_mut(); + let r2 = s.borrow_mut(); +} +``` + +compiles but panics with the following error when we `cargo run`: + +```text + Finished dev [unoptimized + debuginfo] target(s) in 0.83 secs + Running `target/debug/refcell` +thread 'main' panicked at 'already borrowed: BorrowMutError', +/stable-dist-rustc/build/src/libcore/result.rs:868 +note: Run with `RUST_BACKTRACE=1` for a backtrace. +``` + +This runtime `BorrowMutError` is similar to the compiler error: it says we've +already borrowed `s` mutably once, so we're not allowed to borrow it again. We +aren't getting around the borrowing rules, we're just choosing to have Rust +enforce them at runtime instead of compile time. You could choose to use +`RefCell` everywhere all the time, but in addition to having to type +`RefCell` a lot, you'd find out about possible problems later (possibly in +production rather than during development). Also, checking the borrowing rules +while your program is running has a performance penalty. + +So why would we choose to make the tradeoffs that using `RefCell` involves? +Well, remember when we said that `Rc` has to store immutable data? Given +that `RefCell` is immutable, but has interior mutability, we can combine +`Rc` and `RefCell` to get a type that's both reference counted and +mutable. Listing 15-12 shows an example of how to do that, again going back to +our cons list from Listing 15-9. In this example, the type we're filling in for +`T` is `Rc>`: + +
+Filename: src/main.rs + +```rust +#[derive(Debug)] +enum List { + Cons(T, Rc>), + Nil, +} + +use List::{Cons, Nil}; +use std::rc::Rc; +use std::cell::RefCell; + +fn main() { + let value = Rc::new(RefCell::new(5)); + + let a = Cons(value.clone(), Rc::new(Nil)); + let shared_list = Rc::new(a); + + let b = Cons(Rc::new(RefCell::new(6)), shared_list.clone()); + let c = Cons(Rc::new(RefCell::new(10)), shared_list.clone()); + + *value.borrow_mut() += 10; + + println!("shared_list after = {:?}", shared_list); + println!("b after = {:?}", b); + println!("c after = {:?}", c); +} +``` + +
+ +Listing 15-12: Using `Rc>` to create a `List` that we can mutate + +
+
+ +We're creating a value, which is an instance of `T`. We're storing it in a +variable named `value` because we want to be able to access it directly later. +Then we create a `List` in `a` that has a `Cons` variant that holds `value`, +and `value` needs to be cloned since we want `value` to also have ownership in +addition to `a`. Then we wrap `a` in an `Rc` so that we can create lists `b` +and `c` that start differently but both refer to `a`, similarly to what we did +in Listing 15-9. + +Once we have the lists in `shared_list`, `b`, and `c` created, then we add 10 +to the 5 in `value` by dereferencing the `Rc` and calling `borrow_mut` on +the `RefCell`. + +When we print out `shared_list`, `b`, and `c`, we can see that they all have +the modified value of 15: + +```text +shared_list after = Cons(RefCell { value: 15 }, Nil) +b after = Cons(RefCell { value: 6 }, Cons(RefCell { value: 15 }, Nil)) +c after = Cons(RefCell { value: 10 }, Cons(RefCell { value: 15 }, Nil)) +``` + +This is pretty neat! We didn't have to modify our definition of `List` at +all, since the generic parameter lets us substitute any immutable type. By +using `RefCell`, we satisfy the immutable type requirement since +`RefCell` is outwardly immutable, but we can use the methods on `RefCell` +that provide access to its interior mutability to be able to modify our data +when we need to. The runtime checks of the borrowing rules that `RefCell` +does protect us from data races, and we've decided that we want to trade a bit +of speed for the flexibility in our data structures. + +`RefCell` is not the only standard library type that provides interior +mutability. `Cell` is similar but instead of giving references to the inner +value like `RefCell` does, the value is copied in and out of the `Cell`. +`Mutex` offers interior mutability that is safe to use across threads, and +we'll be discussing its use in the next chapter on concurrency. Check out the +standard library docs for more details on the differences between these types. diff --git a/src/ch15-06-reference-cycles.md b/src/ch15-06-reference-cycles.md new file mode 100644 index 000000000..92352f11c --- /dev/null +++ b/src/ch15-06-reference-cycles.md @@ -0,0 +1,305 @@ +## Creating Reference Cycles and Leaking Memory is Safe + +Rust makes a number of guarantees that we've talked about, for example that +we'll never have a null value, and data races will be disallowed at compile +time. Rust's memory safety guarantees make it more difficult to create memory +that never gets cleaned up, which is known as a *memory leak*. Rust does not +make memory leaks *impossible*, however, preventing memory leaks is *not* one +of Rust's guarantees. In other words, memory leaks are memory safe. + +By using `Rc` and `RefCell`, it is possible to create cycles of +references where items refer to each other in a cycle. This is bad because the +reference count of each item in the cycle will never reach 0, and the values +will never be dropped. Let's take a look at how that might happen and how to +prevent it. + +In Listing 15-13, we're going to continue building on the `List` definition +from Listing 15-12. We've added a `RefCell` to the `Cons` variant's definition +so that we can modify a `Cons` instance after we've created it. We've also +added a `next_item` method to make it convenient for us to access the second +item, if we have a `Cons` variant: + +
+Filename: src/main.rs + +```rust +#[derive(Debug)] +enum List { + Cons(T, RefCell>>), + Nil, +} + +impl List { + fn next_item(&self) -> Option<&RefCell>>> { + match *self { + Cons(_, ref item) => Some(item), + Nil => None, + } + } +} +``` + +
+ +Listing 15-13: A cons list definition that holds a `RefCell` so that we can +modify what a `Cons` variant is referring to + +
+
+ +TODO: insert diagram showing the "shape" of the `Cons` variant? + +Next, in Listing 15-14, we're going to create a `List` value in the variable +`a` that initially is a list of `5, Nil`. Then we'll create a `List` value +in the variable `b` that is a list of the value 10 and then points to the list +in `a`. Finally, we'll modify `a` so that it points to `b` instead of `Nil`, +which will then create a cycle: + +
+Filename: src/main.rs + +```rust +# #[derive(Debug)] +# enum List { +# Cons(T, RefCell>>), +# Nil, +# } +# +# impl List { +# fn next_item(&self) -> Option<&RefCell>>> { +# match *self { +# Cons(_, ref item) => Some(item), +# Nil => None, +# } +# } +# } +# +use List::{Cons, Nil}; +use std::rc::Rc; +use std::cell::RefCell; + +fn main() { + + let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); + + println!("a initial rc count = {}", Rc::strong_count(&a)); + println!("a next item = {:?}", a.next_item()); + + let b = Rc::new(Cons(10, RefCell::new(a.clone()))); + + println!("a rc count after b creation = {}", Rc::strong_count(&a)); + println!("b initial rc count = {}", Rc::strong_count(&b)); + println!("b next item = {:?}", b.next_item()); + + if let Some(ref link) = a.next_item() { + *link.borrow_mut() = b.clone(); + } + + println!("b rc count after changing a = {}", Rc::strong_count(&b)); + println!("a rc count after changing a = {}", Rc::strong_count(&a)); + + // Uncomment the next line to see that we have a cycle; it will + // overflow the stack + // println!("a next item = {:?}", a.next_item()); +} +``` + +
+ +Listing 15-14: Creating a reference cycle of two `List` values pointing to +each other + +
+
+ +We use the `next_item` method to get a reference to the `RefCell` in `a`, which +we put in the variable `link`. Then we use the `borrow_mut` method on the +`RefCell` to change the value inside from an `Rc` that holds a `Nil` value to +the `Rc` in `b`. We've created a reference cycle that looks like: + +TODO: insert diagram showing b and a pointing to each other + +If you uncomment the last `println!`, Rust will try and print this cycle out +with `a` pointing to `b` pointing to `a` and so forth until it overflows the +stack. + +Looking at the results of the `println!` calls before the last one, we'll see +that the reference count of both `a` and `b` are 2 after we change `a` to point +to `b`. At the end of `main`, Rust will try and drop `b` first, which will +decrease the count of the `Rc` by one. However, because `a` is still +referencing that `Rc`, its count is 1 rather than 0, so the memory the `Rc` has +on the heap won't be dropped. It'll just sit there with a count of one, +forever. In this specific case, the program ends right away, so it's not a +problem, but in a more complex program that allocates lots of memory in a cycle +and holds onto it for a long time, this would be a problem. The program would +be using more memory than it needs to be, and might overwhelm the system and +cause it to run out of memory available to use. + +Now, as you can see, creating reference cycles is difficult and inconvenient in +Rust. To be honest, your authors had to look up previous discussions of an +example to get this right. But it's not impossible: preventing memory leaks in +the form of reference cycles is not one of the guarantees Rust makes. If you +have `RefCell` values that contain `Rc` values or similar nested +combinations of types with interior mutability and reference counting, be aware +that you'll have to ensure that you don't create cycles on your. One way of +doing that is using `Weak`. + +### Prevent Reference Cycles: Turn an `Rc` into a `Weak` + +To help with this problem, the Rust standard library contains another smart +pointer type: `Weak`. We've been showing how cloning an `Rc` increases +the `strong_count` of references; `Weak` is a way to reference an `Rc` +that does not increment the `strong_count`: instead it increments the +`weak_count` of references to an `Rc`. When an `Rc` goes out of scope, the +inner value will get dropped if the `strong_count` is 0, even if the +`weak_count` is not 0. When we attempt to use a `Weak` reference, we'll get +an `Option` that will be `Some` if the `Rc` value has not been dropped yet, +and `None` if the `Rc` value has been dropped. + +So in order to make it possible to create lists that point to each other but not create reference cycles, in Listing 15-15, we're going to change our definition of `List` again to hold a `Weak` instead of an `Rc`. + +
+Filename: src/main.rs + +```rust +#[derive(Debug)] +enum List { + Cons(T, RefCell>>), + Nil, +} + +impl List { + fn next_item(&self) -> Option>> { + match *self { + Cons(_, ref n) => (&*n.borrow()).upgrade(), + Nil => None, + } + } +} +``` + +
+ +Listing 15-15: Modifying `List` to have `Weak` references instead of +`Rc` + +
+
+ +We've also modified the `next_item` method: not only does it return `None` when +`self` is `Nil` and doesn't have a `next_item`, it now also returns `None` if +the value that the `Weak` references has been dropped. The `upgrade` method +on a `Weak` value returns `Some` containing an `Rc` if the value has not yet +been dropped and `None` if the value has been dropped. + +TODO: is this bad software design, collapsing two cases that return `None` like this??? + +To create `Weak` values, we call the `Rc::downgrade` associated function, +which takes an `&Rc` as an argument, and gives a `Weak` back. + +Listing 15-16 shows a `main` method where we're trying to create `a` and `b` lists that point to each other, similarly to what we did in Listing 15-14, but this time we won't have a reference cycle and the values will be dropped when they go out of scope at the end of `main`: + +
+ +```rust +# #[derive(Debug)] +# enum List { +# Cons(T, RefCell>>), +# Nil, +# } +# +# impl List { +# fn next_item(&self) -> Option>> { +# match *self { +# Cons(_, ref n) => (&*n.borrow()).upgrade(), +# Nil => None, +# } +# } +# } +# +use List::{Cons, Nil}; +use std::rc::{Rc, Weak}; +use std::cell::RefCell; + +fn main() { + let nil = Rc::new(Nil); + + let a = Rc::new(Cons(5, RefCell::new(Rc::downgrade(&nil)))); + + println!("a.next_item() = {:?}", a.next_item()); + + { + let b = Rc::new(Cons(10, RefCell::new(Rc::downgrade(&a.clone())))); + + if let Cons(_, ref link) = *a { + *link.borrow_mut() = Rc::downgrade(&b.clone()); + } + + println!("a.next_item() = {:?}", a.next_item()); + println!("b.next_item() = {:?}", b.next_item()); + } + + println!("a.next_item() = {:?}", a.next_item()); +} +``` + +
+ +Listing 15-16: Creating `List` values using weak references + +
+
+ +First, we create a variable for the `Rc` that holds the `Nil` value, so that +it's clearer to see that we call `Rc::downgrade` and pass a reference to `nil` +when we create `a`. At that point, we print out the value of `a.next_item()` +and we can see that it's `Some(Nil)`. + +We've added an inner scope in order to demonstrate what happens when `b` goes +out of scope. In the inner scope, we create `b` that has a weak reference to +`a`, and then we modify `a` to have a weak reference to `b` instead of to +`nil`. At the end of the inner scope, we can see that `a` and `b` are pointing +to each other, but through weak references. + +At the end of the inner scope, `b` goes out of scope. The value that the +`Rc` in `b` holds gets dropped, even though `a` still references it, because +the reference in `a` is a weak reference that doesn't count when Rust decides +whether the value in `b` should be dropped or not. At the end of `main` when we +print out `a.next_item()` again, we can see that we now get a `None` value +since the value that the weak reference in `a` was pointing to has been +dropped. Success! We've broken the cycle. + +Add some `println!` statements at various places that display the values that +`Rc::strong_count` and `Rc::weak_count` return for `a` and `b` at different +points in this example to see which parts of the code increase or decrease the +strong or weak counts. + +If you're doing complex things with `Rc`s, you should investigate if it's +possible for you to have a cycle, and insert a `Weak` so that you don't +create cycles and leak memory. The specifics depend on exactly what you're +doing, but luckily, this isn't a Rust-specific idea; all of this translates +over to other reference counting libraries in other languages, so doing some +reading about it should help you. + +## Summary + +We've now covered how you can use different kinds of smart pointers to choose +different guarantees and tradeoffs than those Rust makes with regular +references. `Box` has a known size and points to data allocated on the heap. +`Rc` keeps track of the number of references to data on the heap so that +data can have multiple owners. `RefCell` with its interior mutability gives +us a type that can be used where we need an immutable type, and enforces the +borrowing rules at runtime instead of at compile time. + +We've also discussed the `Deref` and `Drop` traits that enable a lot of smart +pointers' functionality. We explored how it's possible to create a reference +cycle that would cause a memory leak, and how to prevent reference cycles by +using `Weak`. + +If this chapter has piqued your interest and you now want to implement your own +smart pointers, check out [The Nomicon] for even more useful information. + +[The Nomicon]: https://doc.rust-lang.org/stable/nomicon/vec.html + +Next, let's talk about concurrency in Rust. We'll even learn about a few new +smart pointers that can help us with it. From 8a39ec9fb15ae882913c334f81426c2883601e21 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Sun, 26 Feb 2017 19:52:07 -0500 Subject: [PATCH 11/42] Connect Drop a bit more to Rc --- src/ch15-04-rc.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/ch15-04-rc.md b/src/ch15-04-rc.md index be1cb5716..99da32182 100644 --- a/src/ch15-04-rc.md +++ b/src/ch15-04-rc.md @@ -188,11 +188,12 @@ rc after c goes out of scope = 2 We're able to see that `a` has an initial reference count of one. Then each time we call `clone`, the count goes up by one. When `c` goes out of scope, the -count is decreased by one. What we can't see in this example is that when `b` -and then `a` go out of scope at the end of `main`, the count of references to -the list containing 5 and 10 is then 0, and the list is dropped. This strategy -lets us have multiple owners, as the count will ensure that the value remains -valid as long as any of the owners still exist. +count is decreased by one, which happens in the implementation of the `Drop` +trait for `Rc`. What we can't see in this example is that when `b` and then +`a` go out of scope at the end of `main`, the count of references to the list +containing 5 and 10 is then 0, and the list is dropped. This strategy lets us +have multiple owners, as the count will ensure that the value remains valid as +long as any of the owners still exist. In the beginning of this section, we said that `Rc` is for read-only data, that is, the value in an `Rc` must be immutable. If it were mutable, we'd run From d2e6325cb7a1f6dc53bc363d5f6fedd662eadeb9 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Sun, 26 Feb 2017 19:52:57 -0500 Subject: [PATCH 12/42] Multithreaded, one word, is in No Starch's style guide --- dictionary.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/dictionary.txt b/dictionary.txt index 37bc86106..414fd805d 100644 --- a/dictionary.txt +++ b/dictionary.txt @@ -163,6 +163,7 @@ monomorphization Monomorphization monomorphized MoveMessage +multithreaded Mutex namespace namespaced From 8d784f724a765e3c51ae115f37876368d1e0c05e Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Sun, 26 Feb 2017 21:24:22 -0500 Subject: [PATCH 13/42] Finish a sentence --- src/ch15-00-smart-pointers.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index 0fe758eab..eace3d6cd 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -30,7 +30,9 @@ most common ones from the standard library: `Box`, `Rc`, and `RefCell`. Along the way, we'll also cover: * The `Deref` and `Drop` traits that make smart pointers convenient to work with -* The *interior mutability* pattern that lets you... +* The *interior mutability* pattern where an immutable type exposes an API for + mutating an interior value, and the borrowing rules apply at runtime instead + of compile time * Reference cycles, how they can leak memory, and how to prevent them Let's dive in! From 334c10e3f75281bf5240ea3882bbb80beee0843d Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Sun, 26 Feb 2017 21:24:32 -0500 Subject: [PATCH 14/42] Wrap --- src/ch15-06-reference-cycles.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/ch15-06-reference-cycles.md b/src/ch15-06-reference-cycles.md index 92352f11c..0467d45e8 100644 --- a/src/ch15-06-reference-cycles.md +++ b/src/ch15-06-reference-cycles.md @@ -156,7 +156,9 @@ inner value will get dropped if the `strong_count` is 0, even if the an `Option` that will be `Some` if the `Rc` value has not been dropped yet, and `None` if the `Rc` value has been dropped. -So in order to make it possible to create lists that point to each other but not create reference cycles, in Listing 15-15, we're going to change our definition of `List` again to hold a `Weak` instead of an `Rc`. +So in order to make it possible to create lists that point to each other but +not create reference cycles, in Listing 15-15, we're going to change our +definition of `List` again to hold a `Weak` instead of an `Rc`.
Filename: src/main.rs @@ -197,7 +199,10 @@ TODO: is this bad software design, collapsing two cases that return `None` like To create `Weak` values, we call the `Rc::downgrade` associated function, which takes an `&Rc` as an argument, and gives a `Weak` back. -Listing 15-16 shows a `main` method where we're trying to create `a` and `b` lists that point to each other, similarly to what we did in Listing 15-14, but this time we won't have a reference cycle and the values will be dropped when they go out of scope at the end of `main`: +Listing 15-16 shows a `main` method where we're trying to create `a` and `b` +lists that point to each other, similarly to what we did in Listing 15-14, but +this time we won't have a reference cycle and the values will be dropped when +they go out of scope at the end of `main`:
From a251d43d01013308df29fe4acdeff181927a680e Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 27 Feb 2017 18:29:18 -0500 Subject: [PATCH 15/42] Take awesome suggestions from @matthewjasper --- src/ch15-04-rc.md | 27 +++++++------- src/ch15-05-interior-mutability.md | 5 +-- src/ch15-06-reference-cycles.md | 56 +++++++++++++++--------------- 3 files changed, 45 insertions(+), 43 deletions(-) diff --git a/src/ch15-04-rc.md b/src/ch15-04-rc.md index 99da32182..04b87c079 100644 --- a/src/ch15-04-rc.md +++ b/src/ch15-04-rc.md @@ -16,12 +16,11 @@ the room, they'll turn the TV off since it's no longer being used. If someone turns off the TV while others are still watching it, though, the people watching the TV would get mad! -`Rc` is for use when we want to allocate some read-only data on the heap, -share that data between multiple parts of our program, and we can't determine -at compile time which part of our program using this data will finish using it -last. If we knew which part would finish last, we could make that part the -owner of the data and the normal ownership rules enforced at compile time would -kick in. +`Rc` is for use when we want to allocate some data on the heap for multiple +parts of our program to read, and we can't determine at compile time which part +of our program using this data will finish using it last. If we knew which part +would finish last, we could make that part the owner of the data and the normal +ownership rules enforced at compile time would kick in. Note that `Rc` is only for use in single-threaded scenarios; the next chapter on concurrency will cover how to do reference counting in @@ -195,10 +194,12 @@ containing 5 and 10 is then 0, and the list is dropped. This strategy lets us have multiple owners, as the count will ensure that the value remains valid as long as any of the owners still exist. -In the beginning of this section, we said that `Rc` is for read-only data, -that is, the value in an `Rc` must be immutable. If it were mutable, we'd run -into a similar problem with borrowing: two mutable borrows to the same place -can cause data races and inconsistencies. But mutating data is very useful! In -the next section, we'll discuss the interior mutability pattern and the -`RefCell` type that we can use in conjunction with an `Rc` to work with -this restriction on immutability. +In the beginning of this section, we said that `Rc` only allows you to share +data for multiple parts of your program to read through immutable references to +the `T` value the `Rc` contains. If `Rc` let us have a mutable reference, +we'd run into the problem that the borrowing rules disallow that we discussed +in Chapter 4: two mutable borrows to the same place can cause data races and +inconsistencies. But mutating data is very useful! In the next section, we'll +discuss the interior mutability pattern and the `RefCell` type that we can +use in conjunction with an `Rc` to work with this restriction on +immutability. diff --git a/src/ch15-05-interior-mutability.md b/src/ch15-05-interior-mutability.md index 86407c679..2ffbe2329 100644 --- a/src/ch15-05-interior-mutability.md +++ b/src/ch15-05-interior-mutability.md @@ -48,8 +48,9 @@ and `borrow_mut` methods, which are part of the safe API that `RefCell` has. Listing 15-11 shows what it looks like to use `RefCell` with functions that borrow their parameters immutably and mutably. Note that the `data` variable is -declared as immutable with `let data` rather than `let mut data`, yet we're -allowed to mutate the value by using `a_fn_that_mutably_borrows`! +declared as immutable with `let data` rather than `let mut data`, yet +`a_fn_that_mutably_borrows` is allowed to borrow the data mutably and make +changes to the data!
Filename: src/main.rs diff --git a/src/ch15-06-reference-cycles.md b/src/ch15-06-reference-cycles.md index 0467d45e8..1c2bdcc4e 100644 --- a/src/ch15-06-reference-cycles.md +++ b/src/ch15-06-reference-cycles.md @@ -16,8 +16,8 @@ prevent it. In Listing 15-13, we're going to continue building on the `List` definition from Listing 15-12. We've added a `RefCell` to the `Cons` variant's definition so that we can modify a `Cons` instance after we've created it. We've also -added a `next_item` method to make it convenient for us to access the second -item, if we have a `Cons` variant: +added a `tail` method to make it convenient for us to access the second item, +if we have a `Cons` variant:
Filename: src/main.rs @@ -30,7 +30,7 @@ enum List { } impl List { - fn next_item(&self) -> Option<&RefCell>>> { + fn tail(&self) -> Option<&RefCell>>> { match *self { Cons(_, ref item) => Some(item), Nil => None, @@ -66,7 +66,7 @@ which will then create a cycle: # } # # impl List { -# fn next_item(&self) -> Option<&RefCell>>> { +# fn tail(&self) -> Option<&RefCell>>> { # match *self { # Cons(_, ref item) => Some(item), # Nil => None, @@ -83,15 +83,15 @@ fn main() { let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); println!("a initial rc count = {}", Rc::strong_count(&a)); - println!("a next item = {:?}", a.next_item()); + println!("a next item = {:?}", a.tail()); let b = Rc::new(Cons(10, RefCell::new(a.clone()))); println!("a rc count after b creation = {}", Rc::strong_count(&a)); println!("b initial rc count = {}", Rc::strong_count(&b)); - println!("b next item = {:?}", b.next_item()); + println!("b next item = {:?}", b.tail()); - if let Some(ref link) = a.next_item() { + if let Some(ref link) = a.tail() { *link.borrow_mut() = b.clone(); } @@ -100,7 +100,7 @@ fn main() { // Uncomment the next line to see that we have a cycle; it will // overflow the stack - // println!("a next item = {:?}", a.next_item()); + // println!("a next item = {:?}", a.tail()); } ``` @@ -112,8 +112,8 @@ each other
-We use the `next_item` method to get a reference to the `RefCell` in `a`, which -we put in the variable `link`. Then we use the `borrow_mut` method on the +We use the `tail` method to get a reference to the `RefCell` in `a`, which we +put in the variable `link`. Then we use the `borrow_mut` method on the `RefCell` to change the value inside from an `Rc` that holds a `Nil` value to the `Rc` in `b`. We've created a reference cycle that looks like: @@ -171,7 +171,7 @@ enum List { } impl List { - fn next_item(&self) -> Option>> { + fn tail(&self) -> Option>> { match *self { Cons(_, ref n) => (&*n.borrow()).upgrade(), Nil => None, @@ -188,11 +188,11 @@ Listing 15-15: Modifying `List` to have `Weak` references instead of
-We've also modified the `next_item` method: not only does it return `None` when -`self` is `Nil` and doesn't have a `next_item`, it now also returns `None` if -the value that the `Weak` references has been dropped. The `upgrade` method -on a `Weak` value returns `Some` containing an `Rc` if the value has not yet -been dropped and `None` if the value has been dropped. +We've also modified the `tail` method: not only does it return `None` when +`self` is `Nil` and doesn't have a `tail`, it now also returns `None` if the +value that the `Weak` references has been dropped. The `upgrade` method on a +`Weak` value returns `Some` containing an `Rc` if the value has not yet been +dropped and `None` if the value has been dropped. TODO: is this bad software design, collapsing two cases that return `None` like this??? @@ -214,7 +214,7 @@ they go out of scope at the end of `main`: # } # # impl List { -# fn next_item(&self) -> Option>> { +# fn tail(&self) -> Option>> { # match *self { # Cons(_, ref n) => (&*n.borrow()).upgrade(), # Nil => None, @@ -231,20 +231,20 @@ fn main() { let a = Rc::new(Cons(5, RefCell::new(Rc::downgrade(&nil)))); - println!("a.next_item() = {:?}", a.next_item()); + println!("a.tail() = {:?}", a.tail()); { - let b = Rc::new(Cons(10, RefCell::new(Rc::downgrade(&a.clone())))); + let b = Rc::new(Cons(10, RefCell::new(Rc::downgrade(&a)))); if let Cons(_, ref link) = *a { - *link.borrow_mut() = Rc::downgrade(&b.clone()); + *link.borrow_mut() = Rc::downgrade(&b); } - println!("a.next_item() = {:?}", a.next_item()); - println!("b.next_item() = {:?}", b.next_item()); + println!("a.tail() = {:?}", a.tail()); + println!("b.tail() = {:?}", b.tail()); } - println!("a.next_item() = {:?}", a.next_item()); + println!("a.tail() = {:?}", a.tail()); } ``` @@ -257,8 +257,8 @@ Listing 15-16: Creating `List` values using weak references First, we create a variable for the `Rc` that holds the `Nil` value, so that it's clearer to see that we call `Rc::downgrade` and pass a reference to `nil` -when we create `a`. At that point, we print out the value of `a.next_item()` -and we can see that it's `Some(Nil)`. +when we create `a`. At that point, we print out the value of `a.tail()` and we +can see that it's `Some(Nil)`. We've added an inner scope in order to demonstrate what happens when `b` goes out of scope. In the inner scope, we create `b` that has a weak reference to @@ -270,9 +270,9 @@ At the end of the inner scope, `b` goes out of scope. The value that the `Rc` in `b` holds gets dropped, even though `a` still references it, because the reference in `a` is a weak reference that doesn't count when Rust decides whether the value in `b` should be dropped or not. At the end of `main` when we -print out `a.next_item()` again, we can see that we now get a `None` value -since the value that the weak reference in `a` was pointing to has been -dropped. Success! We've broken the cycle. +print out `a.tail()` again, we can see that we now get a `None` value since the +value that the weak reference in `a` was pointing to has been dropped. Success! +We've broken the cycle. Add some `println!` statements at various places that display the values that `Rc::strong_count` and `Rc::weak_count` return for `a` and `b` at different From 3595078107daa4aa959ccadd643134fec1c220c9 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 27 Feb 2017 20:31:46 -0500 Subject: [PATCH 16/42] Start (but not complete) swapping out the weak Weak ex --- src/ch15-06-reference-cycles.md | 94 +++++++++++++++++++++++++++++---- 1 file changed, 83 insertions(+), 11 deletions(-) diff --git a/src/ch15-06-reference-cycles.md b/src/ch15-06-reference-cycles.md index 1c2bdcc4e..a3dc6bdb3 100644 --- a/src/ch15-06-reference-cycles.md +++ b/src/ch15-06-reference-cycles.md @@ -141,8 +141,17 @@ example to get this right. But it's not impossible: preventing memory leaks in the form of reference cycles is not one of the guarantees Rust makes. If you have `RefCell` values that contain `Rc` values or similar nested combinations of types with interior mutability and reference counting, be aware -that you'll have to ensure that you don't create cycles on your. One way of -doing that is using `Weak`. +that you'll have to ensure that you don't create cycles. In the example in +Listing 15-14, the solution would probably be to not write code that could +create cycles like this, since we do want `Cons` variants to own the list they +point to. + +With data structures like graphs, it's sometimes necessary to have references +that create cycles in order to have parent nodes point to their children and +children nodes point back in the opposite direction to their parents, for +example. If one of the directions is expressing ownership and the other isn't, +one way of being able to model the relationship of the data without creating +reference cycles and memory leaks is using `Weak`. Let's explore that next! ### Prevent Reference Cycles: Turn an `Rc` into a `Weak` @@ -156,6 +165,8 @@ inner value will get dropped if the `strong_count` is 0, even if the an `Option` that will be `Some` if the `Rc` value has not been dropped yet, and `None` if the `Rc` value has been dropped. +Instead of the list in Listing 15-14 where each element knows only about the next element, let's say we want a list where the elements know about their next element *and* their previous element. + So in order to make it possible to create lists that point to each other but not create reference cycles, in Listing 15-15, we're going to change our definition of `List` again to hold a `Weak` instead of an `Rc`. @@ -165,25 +176,86 @@ definition of `List` again to hold a `Weak` instead of an `Rc`. ```rust #[derive(Debug)] -enum List { - Cons(T, RefCell>>), - Nil, +enum TreePart { + Branch(RefCell>>, T, RefCell>>), + Leaf(RefCell>>), } -impl List { - fn tail(&self) -> Option>> { +impl TreePart { + fn parent(&self) -> Option>> { match *self { - Cons(_, ref n) => (&*n.borrow()).upgrade(), - Nil => None, + Branch(ref p, _, _) => (&*p.borrow()).upgrade(), + Leaf(ref p) => (&*p.borrow()).upgrade(), } } } + +use TreePart::{Branch, Leaf}; +use std::rc::{Rc, Weak}; +use std::cell::RefCell; + +fn main() { + let leaf = Rc::new(Leaf(RefCell::new(Weak::new()))); + + let sapling = Rc::new(Branch( + RefCell::new(Weak::new()), + 10, + RefCell::new(leaf.clone()) + )); + + if let Leaf(ref parent) = *leaf { + *parent.borrow_mut() = Rc::downgrade(&sapling); + } + + println!("leaf = {:?}", leaf); + println!("leaf parent = {:?}", leaf.parent()); + println!("sapling = {:?}", sapling); + println!("sapling parent = {:?}", sapling.parent()); + + { + let oak = Rc::new(Branch( + RefCell::new(Weak::new()), + 50, + RefCell::new(sapling.clone()) + )); + + if let Branch(ref parent, _, _) = *sapling { + *parent.borrow_mut() = Rc::downgrade(&oak); + } + + println!("leaf = {:?}", leaf); + println!("leaf parent = {:?}", leaf.parent()); + println!("sapling = {:?}", sapling); + println!("sapling parent = {:?}", sapling.parent()); + println!("oak = {:?}", oak); + println!("oak parent = {:?}", oak.parent()); + + assert_eq!(2, Rc::strong_count(&leaf)); + assert_eq!(0, Rc::weak_count(&leaf)); + + assert_eq!(2, Rc::strong_count(&sapling)); + assert_eq!(1, Rc::weak_count(&sapling)); + + assert_eq!(1, Rc::strong_count(&oak)); + assert_eq!(1, Rc::weak_count(&oak)); + } + + println!("leaf = {:?}", leaf); + println!("leaf parent = {:?}", leaf.parent()); + println!("sapling = {:?}", sapling); + println!("sapling parent = {:?}", sapling.parent()); + + assert_eq!(2, Rc::strong_count(&leaf)); + assert_eq!(0, Rc::weak_count(&leaf)); + + assert_eq!(1, Rc::strong_count(&sapling)); + assert_eq!(1, Rc::weak_count(&sapling)); +} ```
-Listing 15-15: Modifying `List` to have `Weak` references instead of -`Rc` +Listing 15-15: TODO rework text around here, get some reviews on this example
From 61d552e2ccf1c5517d7e440d17a72930db5adf45 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Mon, 27 Feb 2017 20:35:50 -0500 Subject: [PATCH 17/42] Clarify why we can't call Drop::drop --- src/ch15-03-drop.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/ch15-03-drop.md b/src/ch15-03-drop.md index b0b0c988a..4ec226b94 100644 --- a/src/ch15-03-drop.md +++ b/src/ch15-03-drop.md @@ -107,10 +107,12 @@ Wait for it... Note that we aren't allowed to call the `drop` method that we defined directly: if we replaced `drop(w)` in Listing 15-7 with `w.drop()`, we'll get a compiler -error that says `explicit destructor calls not allowed`. TODO: why aren't we -allowed to call the drop method directly? - -The definition of `std::mem::drop` is: +error that says `explicit destructor calls not allowed`. We're not allowed to +call `Drop::drop` directly because when Rust inserts its call to `Drop::drop` +automatically when the value goes out of scope, then the value would get +dropped twice. Dropping a value twice could cause an error or corrupt memory, +so Rust doesn't let us. Instead, we can use `std::mem::drop`, whose definition +is: ```rust pub mod std { From 77f697b9aee7b77bb68966c85d5da5ce80b006ba Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Tue, 28 Feb 2017 19:00:50 -0500 Subject: [PATCH 18/42] Make section titles consistent and easier to scan --- src/SUMMARY.md | 4 ++-- src/ch15-04-rc.md | 2 +- src/ch15-05-interior-mutability.md | 4 +++- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/SUMMARY.md b/src/SUMMARY.md index d2a9380b6..d599c679b 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -82,8 +82,8 @@ - [`Box` Points to Data on the Heap and Has a Known Size](ch15-01-box.md) - [The `Deref` Trait Allows Access to the Data Through a Reference](ch15-02-deref.md) - [The `Drop` Trait Runs Code on Cleanup](ch15-03-drop.md) - - [The Reference Counted Smart Pointer `Rc`](ch15-04-rc.md) - - [The Interior Mutability Pattern and `RefCell`](ch15-05-interior-mutability.md) + - [`Rc`, the Reference Counted Smart Pointer](ch15-04-rc.md) + - [`RefCell` and the Interior Mutability Pattern](ch15-05-interior-mutability.md) - [Creating Reference Cycles and Leaking Memory is Safe](ch15-06-reference-cycles.md) - [Concurrency](ch16-00-concurrency.md) diff --git a/src/ch15-04-rc.md b/src/ch15-04-rc.md index 04b87c079..ab54f6ca8 100644 --- a/src/ch15-04-rc.md +++ b/src/ch15-04-rc.md @@ -1,4 +1,4 @@ -## The Reference Counted Smart Pointer `Rc` +## `Rc`, the Reference Counted Smart Pointer In the majority of cases, ownership is very clear: you know exactly which variable owns a given value. However, this isn't always the case; sometimes, diff --git a/src/ch15-05-interior-mutability.md b/src/ch15-05-interior-mutability.md index 2ffbe2329..87f794e3c 100644 --- a/src/ch15-05-interior-mutability.md +++ b/src/ch15-05-interior-mutability.md @@ -1,4 +1,4 @@ -## The Interior Mutability Pattern and `RefCell` +## `RefCell` and the Interior Mutability Pattern *Interior mutability* is a design pattern in Rust for allowing you to mutate data that's immutable. The interior mutability pattern involves using `unsafe` @@ -152,6 +152,8 @@ enforce them at runtime instead of compile time. You could choose to use production rather than during development). Also, checking the borrowing rules while your program is running has a performance penalty. +### Multiple Owners of Mutable Data by Combining `Rc` and `RefCell` + So why would we choose to make the tradeoffs that using `RefCell` involves? Well, remember when we said that `Rc` has to store immutable data? Given that `RefCell` is immutable, but has interior mutability, we can combine From 13b10e7952391d1df354f76438e680db69dfe9db Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Tue, 28 Feb 2017 19:31:01 -0500 Subject: [PATCH 19/42] Rejigger intro --- src/ch15-00-smart-pointers.md | 50 +++++++++++++++++------------------ 1 file changed, 24 insertions(+), 26 deletions(-) diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index eace3d6cd..c8a0667ff 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -1,35 +1,33 @@ # Smart Pointers -Now that we've learned quite a bit of Rust, we can start digging into some more -complicated concepts. In this chapter, we'll learn about a design pattern in -Rust called a *smart pointer*. This pattern allows us to leverage Rust's -ownership and borrowing features to manage all kinds of resources in a safe -way, often without much more syntax than using plain old references. - -So what are smart pointers, anyway? Well, we've learned about references in -Rust in Chapter 4. *Pointer* is a generic programming term for something like a -reference, that is, pointers "point at" data somewhere else. References are a +*Pointer* is a generic programming term for something that refers to a location +that stores some other data. We learned about Rust's references in Chapter 4; +they're a plain sort of pointer indicated by the `&` symbol and borrow the +value that they point to. *Smart pointers* are data structures that act like a +pointer, but also have additional metadata and capabilities, such as reference +counting. The smart pointer pattern originated in C++. In Rust, an additional +difference between plain references and smart pointers is that references are a kind of pointer that only borrow data; by contrast, in many cases, smart -pointers *own* the data that they point to. They also often hold metadata about -the data. Smart pointers have extra capabilities that references don't, hence -the "smart" nickname. +pointers *own* the data that they point to. -We've actually already encountered a few smart pointers in this book, we didn't -call them that by name, though. For example, in a certain sense, `String` and -`Vec` from Chapter 8 are both smart pointers. They own some memory and allow -you to manipulate it, and have metadata (like their capacity) and extra -capabilities or guarantees (`String` data will always be valid UTF-8). Another -good example is `File`, which we used for our I/O project in Chapter 12: it -owns and manages a file handle that the operating system gives us, and allows -us to access the data in the file. +We've actually already encountered a few smart pointers in this book, even +though we didn't call them that by name at the time. For example, in a certain +sense, `String` and `Vec` from Chapter 8 are both smart pointers. They own +some memory and allow you to manipulate it, and have metadata (like their +capacity) and extra capabilities or guarantees (`String` data will always be +valid UTF-8). Another good example is `File`, which we used for our I/O project +in Chapter 12: it owns and manages a file handle that the operating system +gives us, and allows us to access the data in the file. The characteristics +that distinguish a smart pointer from an ordinary struct are that smart +pointers implement the `Deref` and `Drop` traits, and in this chapter we'll be +discussing both of those traits and why they're important to smart pointers. -Given that this is a general design pattern in Rust, this chapter won't cover -every smart pointer that exists. Many libraries will build their own as well, -and you may write some for your own code. The ones we cover here will be the -most common ones from the standard library: `Box`, `Rc`, and -`RefCell`. Along the way, we'll also cover: +Given that the smart pointer pattern is a general design pattern used +frequently in Rust, this chapter won't cover every smart pointer that exists. +Many libraries have their own and you may write some yourself. The ones we +cover here are the most common ones from the standard library: `Box`, +`Rc`, and `RefCell`. Along the way, we'll also cover: -* The `Deref` and `Drop` traits that make smart pointers convenient to work with * The *interior mutability* pattern where an immutable type exposes an API for mutating an interior value, and the borrowing rules apply at runtime instead of compile time From aa03fa1eebf644c3f48a07702cad33acca955cca Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Tue, 28 Feb 2017 20:14:06 -0500 Subject: [PATCH 20/42] More rejiggering because of @ScottAbbey's excellent comments <3 --- src/ch15-01-box.md | 13 +++++----- src/ch15-02-deref.md | 60 ++++++++++++++++++++++++++------------------ src/ch15-03-drop.md | 29 +++++++++++---------- 3 files changed, 58 insertions(+), 44 deletions(-) diff --git a/src/ch15-01-box.md b/src/ch15-01-box.md index 62cb39e2a..e001aa6bf 100644 --- a/src/ch15-01-box.md +++ b/src/ch15-01-box.md @@ -1,10 +1,9 @@ ## `Box` Points to Data on the Heap and Has a Known Size -The most straightforward smart pointer is a *box*, whose type is more properly -written as `Box`. Boxes allow you to put a single value on the heap, and the -pointer to that value lives on the stack. (We talked about the stack vs. the -heap in Chapter 4.) Listing 15-1 shows how to use a box to store an `i32` on -the heap: +The most straightforward smart pointer is a *box*, whose type is written +`Box`. Boxes allow you to put a single value on the heap, and the pointer to +that value lives on the stack. (We talked about the stack vs. the heap in +Chapter 4.) Listing 15-1 shows how to use a box to store an `i32` on the heap:
Filename: src/main.rs @@ -26,7 +25,7 @@ Listing 15-1: Storing an `i32` value on the heap using a box This will print `b = 5`. In this case, we can access the data in the box in a similar way as we would if this data was on the stack. Just like any value that has ownership of data, when a box goes out of scope like `b` does at the end of -`main`, it will be deallocated. The deallocation happens for both he box +`main`, it will be deallocated. The deallocation happens for both the box (stored on the stack) and the data it points to (stored on the heap). Putting a single value on the heap isn't very useful, so you won't use boxes by @@ -124,7 +123,7 @@ forth. Therefore, the most space a `Message` value will need is the space it would take to store the largest of its variants. Contrast this to what happens when the Rust compiler looks at a recursive type -like the `List` in Listing 15-2. The compiler tries to figure out how much +like `List` in Listing 15-2. The compiler tries to figure out how much memory is needed to store value of `List`, and starts by looking at the `Cons` variant. The `Cons` variant holds a value of type `T` and a value of type `List`, so it can use however much the size of `T` is plus the size of diff --git a/src/ch15-02-deref.md b/src/ch15-02-deref.md index 24b431735..8916eba21 100644 --- a/src/ch15-02-deref.md +++ b/src/ch15-02-deref.md @@ -78,7 +78,7 @@ Most of this should look familiar: a struct, a trait implementation, and a main function that creates an instance of the struct. There is one part we haven't explained thoroughly yet: similarly to Chapter 13 when we looked at the Iterator trait with the `type Item`, the `type Target = T;` syntax is defining -an associated type, which is covered in more detail in Chapter 20. Don't worry +an associated type, which is covered in more detail in Chapter 19. Don't worry about that part of the example too much; it is a slightly different way of declaring a generic parameter. @@ -112,11 +112,13 @@ why it's necessary to dereference the result of the method is that if the Rust tends to favor explicitness over implicitness, but one case where this does not hold true is *deref coercions* of arguments to functions and methods. -A deref coercion will automatically convert references to pointers or smart -pointers, when passed to functions or methods, into references to the pointer's -contents if needed to match the types of the parameters defined in the -signature. Deref coercion was added to Rust to make calling functions and -methods not need as many explicit references and dereferences with `&` and `*`. +A deref coercion will automatically convert a reference to a pointer or a smart +pointer into a reference to that pointer's contents. A deref coercion happens +when a value is passed to a function or method, and only happens if it's needed +to get the type of the value passed in to match the type of the parameter +defined in the signature. Deref coercion was added to Rust to make calling +functions and methods not need as many explicit references and dereferences +with `&` and `*`. Using our `Mp3` struct from Listing 15-5, here's the signature of a function to compress mp3 audio data that takes a slice of `u8`: @@ -127,29 +129,39 @@ fn compress_mp3(audio: &[u8]) -> Vec { } ``` -Because of deref coercion and our implementation of the `Deref` trait on `Mp3`, -we can call this function with the data in `my_favorite_song` by using this -code: +If Rust didn't have deref coercion, in order to call this function with the +audio data in `my_favorite_song`, we'd have to write: + +```rust,ignore +compress_mp3(my_favorite_song.audio.as_slice()) +``` + +That is, we'd have to explicitly say that we want the data in the `audio` field +of `my_favorite_song` and that we want a slice referring to the whole +`Vec`. If there were a lot of places where we'd want process the `audio` +data in a similar manner, `.audio.as_slice()` would be wordy and repetitive. + +However, because of deref coercion and our implementation of the `Deref` trait +on `Mp3`, we can call this function with the data in `my_favorite_song` by +using this code: ```rust,ignore let result = compress_mp3(&my_favorite_song); ``` -Without deref coercion and our `Deref` implementation on `Mp3`, we would have -to write `compress_mp3(my_favorite_song.audio.as_slice())` in order to call -`compress_mp3` with a slice of the audio data. Deref coercion means that Rust -can use its knowledge of our `Deref` implementation, namely: Rust knows that -`Mp3` implements the `Deref` trait and returns `&Vec` from the `deref` -method. Rust also knows the standard library implements the `Deref` trait on -`Vec` to return `&[T]` from the `deref` method (and we can find that out too -by looking at the API documentation for `Vec`). So, at compile time, Rust -will see that it can use `Deref::deref` twice to turn `&Mp3` into `&Vec` -and then into `&[T]` to match the signature of `compress_mp3`. That means we -get to do less typing! Rust will analyze types through `Deref::deref` as many -times as it needs to in order to get a reference to match the parameter's type, -when the `Deref` trait is defined for the types involved. The indirection is -resolved at compile time, so there is no run-time penalty for taking advantage -of deref coercion. +Just an `&` and the instance, nice! We can treat our smart pointer as if it was +a regular reference. Deref coercion means that Rust can use its knowledge of +our `Deref` implementation, namely: Rust knows that `Mp3` implements the +`Deref` trait and returns `&Vec` from the `deref` method. Rust also knows +the standard library implements the `Deref` trait on `Vec` to return `&[T]` +from the `deref` method (and we can find that out too by looking at the API +documentation for `Vec`). So, at compile time, Rust will see that it can use +`Deref::deref` twice to turn `&Mp3` into `&Vec` and then into `&[T]` to +match the signature of `compress_mp3`. That means we get to do less typing! +Rust will analyze types through `Deref::deref` as many times as it needs to in +order to get a reference to match the parameter's type, when the `Deref` trait +is defined for the types involved. The indirection is resolved at compile time, +so there is no run-time penalty for taking advantage of deref coercion. There's also a `DerefMut` trait for overriding `*` on `&mut T` for use in assignment in the same fashion that we use `Deref` to override `*` on `&T`s. diff --git a/src/ch15-03-drop.md b/src/ch15-03-drop.md index 4ec226b94..befbaa9c8 100644 --- a/src/ch15-03-drop.md +++ b/src/ch15-03-drop.md @@ -4,9 +4,10 @@ The other trait that's important to the smart pointer pattern is the `Drop` trait. `Drop` lets us run some code when a value is about to go out of scope. This is especially useful for smart pointers that manage a resource as opposed to those that manage memory: often resources like files or network connections -need to be closed when our code is done with them. In other languages, if we -forget to call code to close these kinds of resources, the system our code is -running on might get overloaded and crash. +need to be closed when our code is done with them. In other languages, we have +to remember to call code to close these kinds of resources every time we finish +using an instance of one. If we forget, the system our code is running on might +get overloaded and crash. In Rust, we can specify that some code should be run when a value goes out of scope. The compiler will insert this code automatically. That means we don't @@ -18,8 +19,9 @@ implementing the `Drop` trait. The `Drop` trait requires us to implement one method named `drop` that takes a mutable reference to `self`. Listing 15-6 shows a `WebSocket` struct that doesn't actually connect to -anything, but it prints out `Closing the socket!` when we create the struct and -when it goes out of scope so that we can see when this code gets run: +anything, but we're printing out `Websocket created.` right after we create the +struct and `Closing the socket!` when the instance goes out of scope so that we +can see when each piece of code gets run:
Filename: src/main.rs @@ -117,24 +119,25 @@ is: ```rust pub mod std { pub mod mem { - pub fn drop(_x: T) { } + pub fn drop(x: T) { } } } ``` This function is generic over any type `T`, so we can pass any value to it. The function doesn't actually have anything in its body, so it doesn't use its -parameter. The parameter is named `_x` because the `_` is a signal to the -compiler that we're intentionally not using the parameter, so it doesn't need -to warn us that we're not using it. The reason this empty function is useful is -that `drop` takes ownership of its parameter, which means the value gets -dropped at the end of this function when it goes out of scope. +parameter. The reason this empty function is useful is that `drop` takes +ownership of its parameter, which means the value in `x` gets dropped at the +end of this function when `x` goes out of scope. Code specified in a `Drop` trait implementation can be used for many reasons to make cleanup convenient and safe: we could use it to create our own memory allocator, for instance! By using the `Drop` trait and Rust's ownership system, -we can't mess up and forget to clean up, or clean up a value that's still in -use. The ownership system makes sure that we call `drop` at the right time. +we don't have to remember to clean up after ourselves since Rust takes care of +it automatically. We'll get compiler errors if we write code that would clean +up a value that's still in use, since the ownership system that makes sure +references are always valid will also make sure that `drop` only gets called +one time when the value is no longer being used. Now that we've gone over `Box` and some of the characteristics of smart pointers, let's talk about a few other smart pointers defined in the standard From 6672fd6d99e14c3c6bb356d8df73375b283fd80a Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Tue, 28 Feb 2017 20:53:02 -0500 Subject: [PATCH 21/42] Another attempt at the Weak example --- src/ch15-06-reference-cycles.md | 105 +++++++++++++++++++------------- 1 file changed, 64 insertions(+), 41 deletions(-) diff --git a/src/ch15-06-reference-cycles.md b/src/ch15-06-reference-cycles.md index a3dc6bdb3..558940ecd 100644 --- a/src/ch15-06-reference-cycles.md +++ b/src/ch15-06-reference-cycles.md @@ -176,80 +176,103 @@ definition of `List` again to hold a `Weak` instead of an `Rc`. ```rust #[derive(Debug)] -enum TreePart { - Branch(RefCell>>, T, RefCell>>), - Leaf(RefCell>>), +struct Node { + parent: RefCell>>, + children: RefCell>>>, + value: T, } -impl TreePart { - fn parent(&self) -> Option>> { - match *self { - Branch(ref p, _, _) => (&*p.borrow()).upgrade(), - Leaf(ref p) => (&*p.borrow()).upgrade(), - } +impl Node { + fn parent(&self) -> Option>> { + self.parent.borrow().upgrade() } } -use TreePart::{Branch, Leaf}; use std::rc::{Rc, Weak}; use std::cell::RefCell; fn main() { - let leaf = Rc::new(Leaf(RefCell::new(Weak::new()))); + let leaf = Rc::new(Node { + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![]), + value: 0, + }); - let sapling = Rc::new(Branch( - RefCell::new(Weak::new()), - 10, - RefCell::new(leaf.clone()) - )); + let another_leaf = Rc::new(Node { + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![]), + value: 10, + }); - if let Leaf(ref parent) = *leaf { - *parent.borrow_mut() = Rc::downgrade(&sapling); - } + let branch = Rc::new(Node { + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![leaf.clone(), another_leaf.clone()]), + value: 50, + }); + + *leaf.parent.borrow_mut() = Rc::downgrade(&branch); + *another_leaf.parent.borrow_mut() = Rc::downgrade(&branch); println!("leaf = {:?}", leaf); println!("leaf parent = {:?}", leaf.parent()); - println!("sapling = {:?}", sapling); - println!("sapling parent = {:?}", sapling.parent()); + + println!("another_leaf = {:?}", another_leaf); + println!("another_leaf parent = {:?}", another_leaf.parent()); + + println!("branch = {:?}", branch); + println!("branch parent = {:?}", branch.parent()); { - let oak = Rc::new(Branch( - RefCell::new(Weak::new()), - 50, - RefCell::new(sapling.clone()) - )); + let another_branch = Rc::new(Node { + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![branch.clone()]), + value: 70, + }); - if let Branch(ref parent, _, _) = *sapling { - *parent.borrow_mut() = Rc::downgrade(&oak); - } + *branch.parent.borrow_mut() = Rc::downgrade(&another_branch); println!("leaf = {:?}", leaf); println!("leaf parent = {:?}", leaf.parent()); - println!("sapling = {:?}", sapling); - println!("sapling parent = {:?}", sapling.parent()); - println!("oak = {:?}", oak); - println!("oak parent = {:?}", oak.parent()); + + println!("another_leaf = {:?}", another_leaf); + println!("another_leaf parent = {:?}", another_leaf.parent()); + + println!("branch = {:?}", branch); + println!("branch parent = {:?}", branch.parent()); + + println!("another_branch = {:?}", another_branch); + println!("another_branch parent = {:?}", another_branch.parent()); assert_eq!(2, Rc::strong_count(&leaf)); assert_eq!(0, Rc::weak_count(&leaf)); - assert_eq!(2, Rc::strong_count(&sapling)); - assert_eq!(1, Rc::weak_count(&sapling)); + assert_eq!(2, Rc::strong_count(&another_leaf)); + assert_eq!(0, Rc::weak_count(&another_leaf)); - assert_eq!(1, Rc::strong_count(&oak)); - assert_eq!(1, Rc::weak_count(&oak)); + assert_eq!(2, Rc::strong_count(&branch)); + assert_eq!(2, Rc::weak_count(&branch)); + + assert_eq!(1, Rc::strong_count(&another_branch)); + assert_eq!(1, Rc::weak_count(&another_branch)); } println!("leaf = {:?}", leaf); println!("leaf parent = {:?}", leaf.parent()); - println!("sapling = {:?}", sapling); - println!("sapling parent = {:?}", sapling.parent()); + + println!("another_leaf = {:?}", another_leaf); + println!("another_leaf parent = {:?}", another_leaf.parent()); + + println!("branch = {:?}", branch); + println!("branch parent = {:?}", branch.parent()); assert_eq!(2, Rc::strong_count(&leaf)); assert_eq!(0, Rc::weak_count(&leaf)); - assert_eq!(1, Rc::strong_count(&sapling)); - assert_eq!(1, Rc::weak_count(&sapling)); + assert_eq!(2, Rc::strong_count(&another_leaf)); + assert_eq!(0, Rc::weak_count(&another_leaf)); + + assert_eq!(1, Rc::strong_count(&branch)); + assert_eq!(2, Rc::weak_count(&branch)); } ``` From bf0292430ef345c4b84b75aa344eeb6ea9822d95 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 1 Mar 2017 13:20:42 -0500 Subject: [PATCH 22/42] Set up example about borrowing rules on refcell better --- src/ch15-05-interior-mutability.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/ch15-05-interior-mutability.md b/src/ch15-05-interior-mutability.md index 87f794e3c..ee0c04148 100644 --- a/src/ch15-05-interior-mutability.md +++ b/src/ch15-05-interior-mutability.md @@ -95,8 +95,11 @@ the `RefCell` with the `borrow_mut` method, and the function `a_fn_that_mutably_borrows` is allowed to change the value. We can see that the next time we print out the value, it's 6 instead of 5. -Recall that because of the borrowing rules, this code trying to create two -mutable borrows in the same scope won't compile: +### Borrowing Rules are Checked at Runtime on `RefCell` + +Recall from Chapter 4 that because of the borrowing rules, this code using +regular references that tries to create two mutable borrows in the same scope +won't compile: ```rust,ignore let mut s = String::from("hello"); @@ -122,11 +125,11 @@ error[E0499]: cannot borrow `s` as mutable more than once at a time In contrast, using `RefCell` and calling `borrow_mut` twice in the same scope *will* compile, but it will panic at runtime instead. This code: -```rust,ignore +```rust,should_panic use std::cell::RefCell; fn main() { - let mut s = RefCell::new(String::from("hello")); + let s = RefCell::new(String::from("hello")); let r1 = s.borrow_mut(); let r2 = s.borrow_mut(); From b460d0056c898041930ca493b7abe426408f5366 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 1 Mar 2017 13:28:16 -0500 Subject: [PATCH 23/42] Remove unnecessary sentence --- src/ch15-06-reference-cycles.md | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/ch15-06-reference-cycles.md b/src/ch15-06-reference-cycles.md index 558940ecd..0a2a3cae1 100644 --- a/src/ch15-06-reference-cycles.md +++ b/src/ch15-06-reference-cycles.md @@ -136,15 +136,13 @@ be using more memory than it needs to be, and might overwhelm the system and cause it to run out of memory available to use. Now, as you can see, creating reference cycles is difficult and inconvenient in -Rust. To be honest, your authors had to look up previous discussions of an -example to get this right. But it's not impossible: preventing memory leaks in -the form of reference cycles is not one of the guarantees Rust makes. If you -have `RefCell` values that contain `Rc` values or similar nested -combinations of types with interior mutability and reference counting, be aware -that you'll have to ensure that you don't create cycles. In the example in -Listing 15-14, the solution would probably be to not write code that could -create cycles like this, since we do want `Cons` variants to own the list they -point to. +Rust. But it's not impossible: preventing memory leaks in the form of reference +cycles is not one of the guarantees Rust makes. If you have `RefCell` values +that contain `Rc` values or similar nested combinations of types with +interior mutability and reference counting, be aware that you'll have to ensure +that you don't create cycles. In the example in Listing 15-14, the solution +would probably be to not write code that could create cycles like this, since +we do want `Cons` variants to own the list they point to. With data structures like graphs, it's sometimes necessary to have references that create cycles in order to have parent nodes point to their children and From 5c6c1ab2d739cc10c99733e8fa4e45c979e90bd9 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 1 Mar 2017 13:30:20 -0500 Subject: [PATCH 24/42] Fix capitalization --- src/ch15-03-drop.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ch15-03-drop.md b/src/ch15-03-drop.md index befbaa9c8..54dee0e68 100644 --- a/src/ch15-03-drop.md +++ b/src/ch15-03-drop.md @@ -19,7 +19,7 @@ implementing the `Drop` trait. The `Drop` trait requires us to implement one method named `drop` that takes a mutable reference to `self`. Listing 15-6 shows a `WebSocket` struct that doesn't actually connect to -anything, but we're printing out `Websocket created.` right after we create the +anything, but we're printing out `WebSocket created.` right after we create the struct and `Closing the socket!` when the instance goes out of scope so that we can see when each piece of code gets run: From e4658cad15f47cfd7c2d1af1ac52ed88dd8a0cc1 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 1 Mar 2017 13:41:52 -0500 Subject: [PATCH 25/42] Remove File since it doesn't implement Deref --- src/ch15-00-smart-pointers.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index c8a0667ff..8c83fae2b 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -15,12 +15,10 @@ though we didn't call them that by name at the time. For example, in a certain sense, `String` and `Vec` from Chapter 8 are both smart pointers. They own some memory and allow you to manipulate it, and have metadata (like their capacity) and extra capabilities or guarantees (`String` data will always be -valid UTF-8). Another good example is `File`, which we used for our I/O project -in Chapter 12: it owns and manages a file handle that the operating system -gives us, and allows us to access the data in the file. The characteristics -that distinguish a smart pointer from an ordinary struct are that smart -pointers implement the `Deref` and `Drop` traits, and in this chapter we'll be -discussing both of those traits and why they're important to smart pointers. +valid UTF-8). The characteristics that distinguish a smart pointer from an +ordinary struct are that smart pointers implement the `Deref` and `Drop` +traits, and in this chapter we'll be discussing both of those traits and why +they're important to smart pointers. Given that the smart pointer pattern is a general design pattern used frequently in Rust, this chapter won't cover every smart pointer that exists. From c981fc05182944fb6e7ca2759dea72c36d84a12c Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 1 Mar 2017 13:44:27 -0500 Subject: [PATCH 26/42] Remove sentence about box being on the stack; not quite true --- src/ch15-01-box.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ch15-01-box.md b/src/ch15-01-box.md index e001aa6bf..1268c710c 100644 --- a/src/ch15-01-box.md +++ b/src/ch15-01-box.md @@ -1,9 +1,9 @@ ## `Box` Points to Data on the Heap and Has a Known Size The most straightforward smart pointer is a *box*, whose type is written -`Box`. Boxes allow you to put a single value on the heap, and the pointer to -that value lives on the stack. (We talked about the stack vs. the heap in -Chapter 4.) Listing 15-1 shows how to use a box to store an `i32` on the heap: +`Box`. Boxes allow you to put a single value on the heap (we talked about +the stack vs. the heap in Chapter 4). Listing 15-1 shows how to use a box to +store an `i32` on the heap:
Filename: src/main.rs From 84255f96eb50549e3131fdabbfbba98799c83753 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 1 Mar 2017 15:56:19 -0500 Subject: [PATCH 27/42] Address most of aturon's comments --- src/ch15-03-drop.md | 17 +++++---- src/ch15-05-interior-mutability.md | 58 +++++++++++++++++++----------- 2 files changed, 48 insertions(+), 27 deletions(-) diff --git a/src/ch15-03-drop.md b/src/ch15-03-drop.md index 54dee0e68..e976f3f2e 100644 --- a/src/ch15-03-drop.md +++ b/src/ch15-03-drop.md @@ -2,14 +2,17 @@ The other trait that's important to the smart pointer pattern is the `Drop` trait. `Drop` lets us run some code when a value is about to go out of scope. -This is especially useful for smart pointers that manage a resource as opposed -to those that manage memory: often resources like files or network connections -need to be closed when our code is done with them. In other languages, we have -to remember to call code to close these kinds of resources every time we finish -using an instance of one. If we forget, the system our code is running on might -get overloaded and crash. +The `Drop` trait is more generally useful than just smart pointers. For +example, the `Drop` trait is often used on structs that manage a resource: +often resources like files or network connections need to be closed when our +code is done with them. We're discussing `Drop` in the context of smart +pointers, though, because the functionality of the `Drop` trait is almost +always used when implementing smart pointers. -In Rust, we can specify that some code should be run when a value goes out of +In some other languages, we have to remember to call code to free the memory or +resource every time we finish using an instance of a smart pointer. If we +forget, the system our code is running on might get overloaded and crash. In +Rust, we can specify that some code should be run when a value goes out of scope. The compiler will insert this code automatically. That means we don't need to remember to put this code everywhere we're done with an instance of these types, but we still won't leak resources! diff --git a/src/ch15-05-interior-mutability.md b/src/ch15-05-interior-mutability.md index ee0c04148..15fac4e9d 100644 --- a/src/ch15-05-interior-mutability.md +++ b/src/ch15-05-interior-mutability.md @@ -1,11 +1,14 @@ ## `RefCell` and the Interior Mutability Pattern *Interior mutability* is a design pattern in Rust for allowing you to mutate -data that's immutable. The interior mutability pattern involves using `unsafe` -code inside a data structure to bend Rust's usual rules around mutation and -borrowing. We haven't yet covered unsafe code, we will in Chapter 20. The -`unsafe` code is then wrapped in a safe API, and the outer type is still -immutable. +data even though there are immutable references to that data, which would +normally be disallowed by the borrowing rules. The interior mutability pattern +involves using `unsafe` code inside a data structure to bend Rust's usual rules +around mutation and borrowing. We haven't yet covered unsafe code; we will in +Chapter 19. The interior mutability pattern is used when you can ensure that +the borrowing rules will be followed at runtime, even though the compiler can't +ensure that. The `unsafe` code involved is then wrapped in a safe API, and the +outer type is still immutable. Let's explore this by looking at the `RefCell` type that follows the interior mutability pattern. @@ -27,14 +30,18 @@ With references, if you break these rules, you'll get a compiler error. With `RefCell`, if you break these rules, you'll get a `panic!`. Static analysis, like the Rust compiler performs, is inherently conservative. -That is, if Rust accepts an incorrect program, people would not be able to -trust in the guarantees Rust makes. If Rust rejects a correct program, the -programmer will be inconvenienced, but nothing catastrophic can occur. -`RefCell` is useful in two situations: +There are properties of code that are impossible to detect by analyzing the +code: the most famous is the Halting Problem, which is out of scope of this +book but an interesting topic to research if you're interested. -1. When you know that the borrowing rules are respected, but when the compiler - can't understand that that's true. -2. When you need interior mutability. +Because some analysis is impossible, the Rust compiler does not try to even +guess if it can't be sure, so it's conservative and sometimes rejects correct +programs that would not actually violate Rust's guarantees. Put another way, if +Rust accepts an incorrect program, people would not be able to trust in the +guarantees Rust makes. If Rust rejects a correct program, the programmer will +be inconvenienced, but nothing catastrophic can occur. `RefCell` is useful +when you know that the borrowing rules are respected, but the compiler can't +understand that that's true. Similarly to `Rc`, `RefCell` is only for use in single-threaded scenarios. We'll talk about how to get the functionality of `RefCell` in a @@ -66,11 +73,15 @@ fn a_fn_that_mutably_borrows(b: &mut i32) { *b += 1; } +fn demo(r: &RefCell) { + a_fn_that_immutably_borrows(&r.borrow()); + a_fn_that_mutably_borrows(&mut r.borrow_mut()); + a_fn_that_immutably_borrows(&r.borrow()); +} + fn main() { let data = RefCell::new(5); - a_fn_that_immutably_borrows(&data.borrow()); - a_fn_that_mutably_borrows(&mut data.borrow_mut()); - a_fn_that_immutably_borrows(&data.borrow()); + demo(&data); } ``` @@ -88,12 +99,19 @@ a is 5 a is 6 ``` -Here, we've created a new `RefCell` containing the value 5. We can get an -immutable reference to the value inside the `RefCell` by calling the `borrow` -method. More interestingly, we can get a mutable reference to the value inside -the `RefCell` with the `borrow_mut` method, and the function +In `main`, we've created a new `RefCell` containing the value 5, and stored +in the variable `data`, declared without the `mut` keyword. We then call the +`demo` function with an immutable reference to `data`: as far as `main` is +concerned, `data` is immutable! + +In the `demo` function, we get an immutable reference to the value inside the +`RefCell` by calling the `borrow` method, and we call +`a_fn_that_immutably_borrows` with that immutable reference. More +interestingly, we can get a *mutable* reference to the value inside the +`RefCell` with the `borrow_mut` method, and the function `a_fn_that_mutably_borrows` is allowed to change the value. We can see that the -next time we print out the value, it's 6 instead of 5. +next time we call `a_fn_that_immutably_borrows` that prints out the value, it's +6 instead of 5. ### Borrowing Rules are Checked at Runtime on `RefCell` From 52d109f1d30ee6bd5a481f5fa2b06ca9703a1744 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Wed, 1 Mar 2017 16:57:53 -0500 Subject: [PATCH 28/42] Try to make examples a bit clearer --- src/ch15-01-box.md | 84 +++++++++++++++++------------- src/ch15-04-rc.md | 34 ++++++------ src/ch15-05-interior-mutability.md | 44 ++++++++-------- src/ch15-06-reference-cycles.md | 64 +++++++++++++---------- 4 files changed, 123 insertions(+), 103 deletions(-) diff --git a/src/ch15-01-box.md b/src/ch15-01-box.md index 1268c710c..fe8bf1264 100644 --- a/src/ch15-01-box.md +++ b/src/ch15-01-box.md @@ -38,25 +38,36 @@ A cons list is a list where each item contains a value and the next item until the end of the list, which is signified by a value called `Nil`. Note that we aren't introducing the idea of "nil" or "null" that we discussed in Chapter 6, this is just a regular enum variant name we're using because it's the canonical -name to use when describing the cons list data structure. +name to use when describing the cons list data structure. Cons lists aren't +used very often in Rust, `Vec` is a better choice most of the time, but +implementing this data structure is useful as an example. + +Here's our first try at defining a cons list as an enum; note that this won't +compile quite yet:
Filename: src/main.rs ```rust,ignore -enum List { - Cons(T, List), +enum List { + Cons(i32, List), Nil, } ```
-Listing 15-2: An enum definition for a cons list data structure +Listing 15-2: The first attempt of defining an enum to represent a cons list +data structure of `i32` values
+We're choosing to implement a cons list that only holds `i32` values, but we +could have chosen to implement it using generics as we discussed in Chapter 10 +to define a cons list concept independent of the type of value stored in the +cons list. + Using a cons list to store the list `1, 2, 3` would look like this: ```rust,ignore @@ -67,13 +78,12 @@ fn main() { } ``` -The first `Cons` value holds `1` and another `List` value. This `List` -value is another `Cons` value that holds `2` and another `List` value. This -is one more `Cons` value that holds `3` and a `List` value, which is finally +The first `Cons` value holds `1` and another `List` value. This `List` +value is another `Cons` value that holds `2` and another `List` value. This +is one more `Cons` value that holds `3` and a `List` value, which is finally `Nil`, the non-recursive variant that signals the end of the list. -However, if we try to compile the above code, we get the error shown in Listing -15-3: +If we try to compile the above code, we get the error shown in Listing 15-3:
@@ -81,9 +91,9 @@ However, if we try to compile the above code, we get the error shown in Listing error[E0072]: recursive type `List` has infinite size --> | -1 | enum List { +1 | enum List { | _^ starting here... -2 | | Cons(T, List), +2 | | Cons(i32, List), 3 | | Nil, 4 | | } | |_^ ...ending here: recursive type has infinite size @@ -100,10 +110,10 @@ Listing 15-3: The error we get when attempting to define a recursive enum
The error says this type 'has infinite size'. Why is that? It's because we've -defined `List` to have a variant that is recursive: it holds another value -of itself. This means Rust can't figure out how much space it needs in order to -store a `List` value. Let's break this down a bit: first let's look at how -Rust decides how much space it needs to store a value of a non-recursive type. +defined `List` to have a variant that is recursive: it holds another value of +itself. This means Rust can't figure out how much space it needs in order to +store a `List` value. Let's break this down a bit: first let's look at how Rust +decides how much space it needs to store a value of a non-recursive type. Recall the `Message` enum we defined in Listing 6-2 when we discussed enum definitions in Chapter 6: @@ -123,15 +133,15 @@ forth. Therefore, the most space a `Message` value will need is the space it would take to store the largest of its variants. Contrast this to what happens when the Rust compiler looks at a recursive type -like `List` in Listing 15-2. The compiler tries to figure out how much -memory is needed to store value of `List`, and starts by looking at the -`Cons` variant. The `Cons` variant holds a value of type `T` and a value of -type `List`, so it can use however much the size of `T` is plus the size of -`List`. To figure out how much memory a `List` needs, it looks at its -variants, starting with the `Cons` variant. The `Cons` variant holds a value of -type `T` and a value of type `List`, and this continues infinitely. Rust -can't figure out how much space to allocate for recursively defined types, so -the compiler gives the error in Listing 15-3. +like `List` in Listing 15-2. The compiler tries to figure out how much memory +is needed to store value of `List`, and starts by looking at the `Cons` +variant. The `Cons` variant holds a value of type `i32` and a value of type +`List`, so `Cons` needs an amount of space equal to the size of an `i32` plus +the size of a `List`. To figure out how much memory a `List` needs, it looks at +its variants, starting with the `Cons` variant. The `Cons` variant holds a +value of type `i32` and a value of type `List`, and this continues infinitely. +Rust can't figure out how much space to allocate for recursively defined types, +so the compiler gives the error in Listing 15-3. The compiler did give a helpful suggestion in the error output: @@ -152,8 +162,8 @@ like so: Filename: src/main.rs ```rust -enum List { - Cons(T, Box>), +enum List { + Cons(i32, Box), Nil, } @@ -169,22 +179,22 @@ fn main() {
-Listing 15-4: Definition of `List` that uses `Box` in order to have a +Listing 15-4: Definition of `List` that uses `Box` in order to have a known size
-The compiler will be able to figure out the size it needs to store a `List` -value. Rust will look at `List`, and again start by looking at the `Cons` -variant. The `Cons` variant will need the size of whatever `T` is, plus the -space to store a `usize`, since a box always has the size of a `usize`, no -matter what it's pointing to. Then Rust looks at the `Nil` variant, which does -not store a value, so `Nil` doesn't need any space. We've broken the infinite, -recursive chain by adding in a box. This is the main area where boxes are -useful: breaking up an infinite data structure so that the compiler can know -what size it is. We'll look at another case where Rust has data of unknown size -in Chapter 17 when we discuss trait objects. +The compiler will be able to figure out the size it needs to store a `List` +value. Rust will look at `List`, and again start by looking at the `Cons` +variant. The `Cons` variant will need the size of `i32` plus the space to store +a `usize`, since a box always has the size of a `usize`, no matter what it's +pointing to. Then Rust looks at the `Nil` variant, which does not store a +value, so `Nil` doesn't need any space. We've broken the infinite, recursive +chain by adding in a box. This is the main area where boxes are useful: +breaking up an infinite data structure so that the compiler can know what size +it is. We'll look at another case where Rust has data of unknown size in +Chapter 17 when we discuss trait objects. Even though you won't be using boxes very often, they are a good way to understand the smart pointer pattern. Two of the aspects of `Box` that are diff --git a/src/ch15-04-rc.md b/src/ch15-04-rc.md index ab54f6ca8..743a7276b 100644 --- a/src/ch15-04-rc.md +++ b/src/ch15-04-rc.md @@ -30,13 +30,13 @@ you'll get a compile-time error. ### Using `Rc` to Share Data Let's return to our cons list example from Listing 15-4. In Listing 15-8, we're -going to try to use `List` as we defined it using `Box`. First we'll -create one list instance that contains 5 and then 10. Next, we want to create -two more lists: one that starts with 3 and continues on to our first list -containing 5 and 10, then another list that starts with 4 and *also* continues -on to our first list containing 5 and 10. In other words, we want two lists -that both share ownership of the third list, which conceptually will be -something like this: +going to try to use `List` as we defined it using `Box`. First we'll create +one list instance that contains 5 and then 10. Next, we want to create two more +lists: one that starts with 3 and continues on to our first list containing 5 +and 10, then another list that starts with 4 and *also* continues on to our +first list containing 5 and 10. In other words, we want two lists that both +share ownership of the third list, which conceptually will be something like +this: ```text b -> 3 ---v @@ -44,15 +44,15 @@ a ------> 5 -> 10 -> Nil c -> 4 ---^ ``` -Trying to implement this using our definition of `List` with `Box` won't +Trying to implement this using our definition of `List` with `Box` won't work:
Filename: src/main.rs ```rust,ignore -enum List { - Cons(T, Box>), +enum List { + Cons(i32, Box), Nil, } @@ -86,7 +86,7 @@ error[E0382]: use of moved value: `a` 13 | let c = Cons(4, Box::new(a)); | ^ value used here after move | - = note: move occurs because `a` has type `List`, which does not + = note: move occurs because `a` has type `List`, which does not implement the `Copy` trait ``` @@ -99,15 +99,15 @@ we'd have to specify lifetime parameters and we'd have to construct elements of a list such that every element lives at least as long as the list itself. Otherwise, the borrow checker won't even let us compile the code. -Instead, we can change our definition of `List` to use `Rc` instead of +Instead, we can change our definition of `List` to use `Rc` instead of `Box` as shown here in Listing 15-9:
Filename: src/main.rs ```rust -enum List { - Cons(T, Rc>), +enum List { + Cons(i32, Rc), Nil, } @@ -123,7 +123,7 @@ fn main() {
-Listing 15-9: A definition of `List` that uses `Rc` +Listing 15-9: A definition of `List` that uses `Rc`
@@ -148,8 +148,8 @@ reference cycles. Filename: src/main.rs ```rust -# enum List { -# Cons(T, Rc>), +# enum List { +# Cons(i32, Rc), # Nil, # } # diff --git a/src/ch15-05-interior-mutability.md b/src/ch15-05-interior-mutability.md index 15fac4e9d..48f7c950c 100644 --- a/src/ch15-05-interior-mutability.md +++ b/src/ch15-05-interior-mutability.md @@ -141,7 +141,7 @@ error[E0499]: cannot borrow `s` as mutable more than once at a time ``` In contrast, using `RefCell` and calling `borrow_mut` twice in the same -scope *will* compile, but it will panic at runtime instead. This code: +scope *will* compile, but it'll panic at runtime instead. This code: ```rust,should_panic use std::cell::RefCell; @@ -180,16 +180,20 @@ Well, remember when we said that `Rc` has to store immutable data? Given that `RefCell` is immutable, but has interior mutability, we can combine `Rc` and `RefCell` to get a type that's both reference counted and mutable. Listing 15-12 shows an example of how to do that, again going back to -our cons list from Listing 15-9. In this example, the type we're filling in for -`T` is `Rc>`: +our cons list from Listing 15-9. In this example, instead of storing `i32` +values in the cons list, we'll be storing `Rc>` values. We want to +store that type so that we can have an owner of the value that's not part of +the list (the multiple owners functionality that `Rc` provides), and so we +can mutate the inner `i32` value (the interior mutability functionality that +`RefCell` provides):
Filename: src/main.rs ```rust #[derive(Debug)] -enum List { - Cons(T, Rc>), +enum List { + Cons(Rc>, Rc), Nil, } @@ -216,18 +220,18 @@ fn main() {
-Listing 15-12: Using `Rc>` to create a `List` that we can mutate +Listing 15-12: Using `Rc>` to create a `List` that we can mutate
-We're creating a value, which is an instance of `T`. We're storing it in a -variable named `value` because we want to be able to access it directly later. -Then we create a `List` in `a` that has a `Cons` variant that holds `value`, -and `value` needs to be cloned since we want `value` to also have ownership in -addition to `a`. Then we wrap `a` in an `Rc` so that we can create lists `b` -and `c` that start differently but both refer to `a`, similarly to what we did -in Listing 15-9. +We're creating a value, which is an instance of `Rc>. We're +storing it in a variable named `value` because we want to be able to access it +directly later. Then we create a `List` in `a` that has a `Cons` variant that +holds `value`, and `value` needs to be cloned since we want `value` to also +have ownership in addition to `a`. Then we wrap `a` in an `Rc` so that we +can create lists `b` and `c` that start differently but both refer to `a`, +similarly to what we did in Listing 15-9. Once we have the lists in `shared_list`, `b`, and `c` created, then we add 10 to the 5 in `value` by dereferencing the `Rc` and calling `borrow_mut` on @@ -242,14 +246,12 @@ b after = Cons(RefCell { value: 6 }, Cons(RefCell { value: 15 }, Nil)) c after = Cons(RefCell { value: 10 }, Cons(RefCell { value: 15 }, Nil)) ``` -This is pretty neat! We didn't have to modify our definition of `List` at -all, since the generic parameter lets us substitute any immutable type. By -using `RefCell`, we satisfy the immutable type requirement since -`RefCell` is outwardly immutable, but we can use the methods on `RefCell` -that provide access to its interior mutability to be able to modify our data -when we need to. The runtime checks of the borrowing rules that `RefCell` -does protect us from data races, and we've decided that we want to trade a bit -of speed for the flexibility in our data structures. +This is pretty neat! By using `RefCell`, we can have an outwardly immutable +`List`, but we can use the methods on `RefCell` that provide access to its +interior mutability to be able to modify our data when we need to. The runtime +checks of the borrowing rules that `RefCell` does protect us from data +races, and we've decided that we want to trade a bit of speed for the +flexibility in our data structures. `RefCell` is not the only standard library type that provides interior mutability. `Cell` is similar but instead of giving references to the inner diff --git a/src/ch15-06-reference-cycles.md b/src/ch15-06-reference-cycles.md index 0a2a3cae1..7bbcd160f 100644 --- a/src/ch15-06-reference-cycles.md +++ b/src/ch15-06-reference-cycles.md @@ -13,30 +13,35 @@ reference count of each item in the cycle will never reach 0, and the values will never be dropped. Let's take a look at how that might happen and how to prevent it. -In Listing 15-13, we're going to continue building on the `List` definition -from Listing 15-12. We've added a `RefCell` to the `Cons` variant's definition -so that we can modify a `Cons` instance after we've created it. We've also -added a `tail` method to make it convenient for us to access the second item, -if we have a `Cons` variant: +In Listing 15-13, we're going to use another variation of the `List` definition +from Listing 15-12. We're going back to storing an `i32` value as the first +element in the `Cons` variant. The second element in the `Cons` variant is now +`RefCell>`: instead of being able to modify the `i32` value this time, +we want to be able to modify which `List` a `Cons` variant is pointing to. +We've also added a `tail` method to make it convenient for us to access the +second item, if we have a `Cons` variant:
Filename: src/main.rs ```rust #[derive(Debug)] -enum List { - Cons(T, RefCell>>), +enum List { + Cons(i32, RefCell>), Nil, } -impl List { - fn tail(&self) -> Option<&RefCell>>> { +impl List { + fn tail(&self) -> Option<&RefCell>> { match *self { Cons(_, ref item) => Some(item), Nil => None, } } } +# use std::rc::Rc; +# use std::cell::RefCell; +# use List::{Cons, Nil}; ```
@@ -49,24 +54,24 @@ modify what a `Cons` variant is referring to TODO: insert diagram showing the "shape" of the `Cons` variant? -Next, in Listing 15-14, we're going to create a `List` value in the variable -`a` that initially is a list of `5, Nil`. Then we'll create a `List` value -in the variable `b` that is a list of the value 10 and then points to the list -in `a`. Finally, we'll modify `a` so that it points to `b` instead of `Nil`, -which will then create a cycle: +Next, in Listing 15-14, we're going to create a `List` value in the variable +`a` that initially is a list of `5, Nil`. Then we'll create a `List` value in +the variable `b` that is a list of the value 10 and then points to the list in +`a`. Finally, we'll modify `a` so that it points to `b` instead of `Nil`, which +will then create a cycle:
Filename: src/main.rs ```rust # #[derive(Debug)] -# enum List { -# Cons(T, RefCell>>), +# enum List { +# Cons(i32, RefCell>), # Nil, # } # -# impl List { -# fn tail(&self) -> Option<&RefCell>>> { +# impl List { +# fn tail(&self) -> Option<&RefCell>> { # match *self { # Cons(_, ref item) => Some(item), # Nil => None, @@ -106,7 +111,7 @@ fn main() {
-Listing 15-14: Creating a reference cycle of two `List` values pointing to +Listing 15-14: Creating a reference cycle of two `List` values pointing to each other
@@ -159,11 +164,14 @@ the `strong_count` of references; `Weak` is a way to reference an `Rc` that does not increment the `strong_count`: instead it increments the `weak_count` of references to an `Rc`. When an `Rc` goes out of scope, the inner value will get dropped if the `strong_count` is 0, even if the -`weak_count` is not 0. When we attempt to use a `Weak` reference, we'll get -an `Option` that will be `Some` if the `Rc` value has not been dropped yet, -and `None` if the `Rc` value has been dropped. +`weak_count` is not 0. To be able to get the value from a `Weak`, we first +have to upgrade it to an `Option>` by using the `upgrade` function. The +result of upgrading a `Weak` will be `Some` if the `Rc` value has not been +dropped yet, and `None` if the `Rc` value has been dropped. -Instead of the list in Listing 15-14 where each element knows only about the next element, let's say we want a list where the elements know about their next element *and* their previous element. +Instead of the list in Listing 15-14 where each element knows only about the +next element, let's say we want a list where the elements know about their next +element *and* their previous element. So in order to make it possible to create lists that point to each other but not create reference cycles, in Listing 15-15, we're going to change our @@ -175,9 +183,9 @@ definition of `List` again to hold a `Weak` instead of an `Rc`. ```rust #[derive(Debug)] struct Node { + value: T, parent: RefCell>>, children: RefCell>>>, - value: T, } impl Node { @@ -191,21 +199,21 @@ use std::cell::RefCell; fn main() { let leaf = Rc::new(Node { + value: 0, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]), - value: 0, }); let another_leaf = Rc::new(Node { + value: 10, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]), - value: 10, }); let branch = Rc::new(Node { + value: 50, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![leaf.clone(), another_leaf.clone()]), - value: 50, }); *leaf.parent.borrow_mut() = Rc::downgrade(&branch); @@ -222,9 +230,9 @@ fn main() { { let another_branch = Rc::new(Node { + value: 70, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![branch.clone()]), - value: 70, }); *branch.parent.borrow_mut() = Rc::downgrade(&another_branch); From 90c380c8c070aec319cf9f0031477924f029a570 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 11:25:07 -0500 Subject: [PATCH 29/42] Try to clarify that RefCell isn't really a smart pointer --- src/ch15-00-smart-pointers.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/ch15-00-smart-pointers.md b/src/ch15-00-smart-pointers.md index 8c83fae2b..3173cc508 100644 --- a/src/ch15-00-smart-pointers.md +++ b/src/ch15-00-smart-pointers.md @@ -23,8 +23,15 @@ they're important to smart pointers. Given that the smart pointer pattern is a general design pattern used frequently in Rust, this chapter won't cover every smart pointer that exists. Many libraries have their own and you may write some yourself. The ones we -cover here are the most common ones from the standard library: `Box`, -`Rc`, and `RefCell`. Along the way, we'll also cover: +cover here are the most common ones from the standard library: + +* `Box`, for allocating values on the heap +* `Rc`, a reference counted type so data can have multiple owners +* `RefCell`, which isn't a smart pointer itself, but manages access to the + smart pointers `Ref` and `RefMut` to enforce the borrowing rules at runtime + instead of compile time + +Along the way, we'll also cover: * The *interior mutability* pattern where an immutable type exposes an API for mutating an interior value, and the borrowing rules apply at runtime instead From 72b4ceb5787c6a6273337217b533038ab9c15e32 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 11:27:28 -0500 Subject: [PATCH 30/42] More RefCell clarification --- src/ch15-05-interior-mutability.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/ch15-05-interior-mutability.md b/src/ch15-05-interior-mutability.md index 48f7c950c..438dd3ba2 100644 --- a/src/ch15-05-interior-mutability.md +++ b/src/ch15-05-interior-mutability.md @@ -52,6 +52,11 @@ context, you'll get a compile time error. With references, we use the `&` and `&mut` syntax to create references and mutable references, respectively. But with `RefCell`, we use the `borrow` and `borrow_mut` methods, which are part of the safe API that `RefCell` has. +`borrow` returns the smart pointer type `Ref`, and `borrow_mut` returns the +smart pointer type `RefMut`. These two types implement `Deref` so that we can +treat them as if they're regular references. `Ref` and `RefMut` track the +borrows dynamically, and their implementation of `Drop` releases the borrow +dynamically. Listing 15-11 shows what it looks like to use `RefCell` with functions that borrow their parameters immutably and mutably. Note that the `data` variable is From d7ade002c2122397551a46923265baf1d744da1d Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 11:32:37 -0500 Subject: [PATCH 31/42] Clarify another instance of immutable data --- src/ch15-05-interior-mutability.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/ch15-05-interior-mutability.md b/src/ch15-05-interior-mutability.md index 438dd3ba2..d27eb69fe 100644 --- a/src/ch15-05-interior-mutability.md +++ b/src/ch15-05-interior-mutability.md @@ -181,16 +181,16 @@ while your program is running has a performance penalty. ### Multiple Owners of Mutable Data by Combining `Rc` and `RefCell` So why would we choose to make the tradeoffs that using `RefCell` involves? -Well, remember when we said that `Rc` has to store immutable data? Given -that `RefCell` is immutable, but has interior mutability, we can combine -`Rc` and `RefCell` to get a type that's both reference counted and -mutable. Listing 15-12 shows an example of how to do that, again going back to -our cons list from Listing 15-9. In this example, instead of storing `i32` -values in the cons list, we'll be storing `Rc>` values. We want to -store that type so that we can have an owner of the value that's not part of -the list (the multiple owners functionality that `Rc` provides), and so we -can mutate the inner `i32` value (the interior mutability functionality that -`RefCell` provides): +Well, remember when we said that `Rc` only lets you have an immutable +reference to `T`? Given that `RefCell` is immutable, but has interior +mutability, we can combine `Rc` and `RefCell` to get a type that's both +reference counted and mutable. Listing 15-12 shows an example of how to do +that, again going back to our cons list from Listing 15-9. In this example, +instead of storing `i32` values in the cons list, we'll be storing +`Rc>` values. We want to store that type so that we can have an +owner of the value that's not part of the list (the multiple owners +functionality that `Rc` provides), and so we can mutate the inner `i32` +value (the interior mutability functionality that `RefCell` provides):
Filename: src/main.rs From 66467333ab9103e6ee75b88cd876b920fd4afac2 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 11:46:11 -0500 Subject: [PATCH 32/42] Use a sillier example than the non-functioning WebSocket --- src/ch15-03-drop.md | 67 +++++++++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 32 deletions(-) diff --git a/src/ch15-03-drop.md b/src/ch15-03-drop.md index e976f3f2e..220e6a24c 100644 --- a/src/ch15-03-drop.md +++ b/src/ch15-03-drop.md @@ -2,18 +2,18 @@ The other trait that's important to the smart pointer pattern is the `Drop` trait. `Drop` lets us run some code when a value is about to go out of scope. -The `Drop` trait is more generally useful than just smart pointers. For -example, the `Drop` trait is often used on structs that manage a resource: -often resources like files or network connections need to be closed when our -code is done with them. We're discussing `Drop` in the context of smart -pointers, though, because the functionality of the `Drop` trait is almost -always used when implementing smart pointers. +Smart pointers perform important cleanup when being dropped, like deallocating +memory or decrementing a reference count. More generally, data types can manage +resources beyond memory, like files or network connections, and use `Drop` to +release those resources when our code is done with them. We're discussing +`Drop` in the context of smart pointers, though, because the functionality of +the `Drop` trait is almost always used when implementing smart pointers. In some other languages, we have to remember to call code to free the memory or resource every time we finish using an instance of a smart pointer. If we forget, the system our code is running on might get overloaded and crash. In Rust, we can specify that some code should be run when a value goes out of -scope. The compiler will insert this code automatically. That means we don't +scope, and the compiler will insert this code automatically. That means we don't need to remember to put this code everywhere we're done with an instance of these types, but we still won't leak resources! @@ -21,36 +21,38 @@ The way we specify code should be run when a value goes out of scope is by implementing the `Drop` trait. The `Drop` trait requires us to implement one method named `drop` that takes a mutable reference to `self`. -Listing 15-6 shows a `WebSocket` struct that doesn't actually connect to -anything, but we're printing out `WebSocket created.` right after we create the -struct and `Closing the socket!` when the instance goes out of scope so that we -can see when each piece of code gets run: +Listing 15-6 shows a `CustomSmartPointer` struct that doesn't actually do +anything, but we're printing out `CustomSmartPointer created.` right after we +create an instance of the struct and `Dropping CustomSmartPointer!` when the +instance goes out of scope so that we can see when each piece of code gets run. +Instead of a `println!` statement, you'd fill in `drop` with whatever cleanup +code your smart pointer needs to run:
Filename: src/main.rs ```rust -struct WebSocket { - uri: String, +struct CustomSmartPointer { + data: String, } -impl Drop for WebSocket { +impl Drop for CustomSmartPointer { fn drop(&mut self) { - println!("Closing the socket!"); + println!("Dropping CustomSmartPointer!"); } } fn main() { - let w = WebSocket { uri: String::from("http://example.com/not-real") }; - println!("WebSocket created."); + let c = CustomSmartPointer { data: String::from("some data") }; + println!("CustomSmartPointer created."); println!("Wait for it..."); } ```
-Listing 15-6: A `WebSocket` struct that implements the `Drop` trait, where we -could put code that would close the socket. +Listing 15-6: A `CustomSmartPointer` struct that implements the `Drop` trait, +where we could put code that would clean up after the `CustomSmartPointer`.
@@ -58,16 +60,17 @@ could put code that would close the socket. The `Drop` trait is in the prelude, so we don't need to import it. The `drop` method implementation calls the `println!`; this is where you'd put the actual code needed to close the socket. In `main`, we create a new instance of -`WebSocket` then print out `WebSocket created.` to be able to see that our code -got to that point at runtime. At the end of `main`, our instance of `WebSocket` -will go out of scope. Note that we didn't call the `drop` method explicitly. +`CustomSmartPointer` then print out `CustomSmartPointer created.` to be able to +see that our code got to that point at runtime. At the end of `main`, our +instance of `CustomSmartPointer` will go out of scope. Note that we didn't call +the `drop` method explicitly. When we run this program, we'll see: ```text -WebSocket created. +CustomSmartPointer created. Wait for it... -Closing the socket! +Dropping CustomSmartPointer! ``` printed to the screen, which shows that Rust automatically called `drop` for us @@ -85,9 +88,9 @@ that it's possible, and `std::mem::drop` is in the prelude so we can just call ```rust,ignore fn main() { - let w = WebSocket { uri: String::from("http://example.com/not-real") }; - println!("WebSocket created."); - drop(w); + let c = CustomSmartPointer { data: String::from("some data") }; + println!("CustomSmartPointer created."); + drop(c); println!("Wait for it..."); } ``` @@ -101,17 +104,17 @@ goes out of scope
Running this code will print the following, showing that the destructor code is -called since `Closing the socket!` is printed between `WebSocket created.` and -`Wait for it...`: +called since `Dropping CustomSmartPointer!` is printed between +`CustomSmartPointer created.` and `Wait for it...`: ```text -WebSocket created. -Closing the socket! +CustomSmartPointer created. +Dropping CustomSmartPointer! Wait for it... ``` Note that we aren't allowed to call the `drop` method that we defined directly: -if we replaced `drop(w)` in Listing 15-7 with `w.drop()`, we'll get a compiler +if we replaced `drop(c)` in Listing 15-7 with `c.drop()`, we'll get a compiler error that says `explicit destructor calls not allowed`. We're not allowed to call `Drop::drop` directly because when Rust inserts its call to `Drop::drop` automatically when the value goes out of scope, then the value would get From 90ba6d3f4db26677820ad8b74c92382173290820 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 15:49:19 -0500 Subject: [PATCH 33/42] Incorporate the Weak example --- src/ch15-06-reference-cycles.md | 365 +++++++++++++++++--------------- 1 file changed, 190 insertions(+), 175 deletions(-) diff --git a/src/ch15-06-reference-cycles.md b/src/ch15-06-reference-cycles.md index 7bbcd160f..ace15083c 100644 --- a/src/ch15-06-reference-cycles.md +++ b/src/ch15-06-reference-cycles.md @@ -158,234 +158,249 @@ reference cycles and memory leaks is using `Weak`. Let's explore that next! ### Prevent Reference Cycles: Turn an `Rc` into a `Weak` -To help with this problem, the Rust standard library contains another smart -pointer type: `Weak`. We've been showing how cloning an `Rc` increases -the `strong_count` of references; `Weak` is a way to reference an `Rc` -that does not increment the `strong_count`: instead it increments the -`weak_count` of references to an `Rc`. When an `Rc` goes out of scope, the -inner value will get dropped if the `strong_count` is 0, even if the -`weak_count` is not 0. To be able to get the value from a `Weak`, we first -have to upgrade it to an `Option>` by using the `upgrade` function. The -result of upgrading a `Weak` will be `Some` if the `Rc` value has not been -dropped yet, and `None` if the `Rc` value has been dropped. +The Rust standard library provides `Weak`, a smart pointer type for use in +situations that have cycles of references but only one direction expresses +ownership. We've been showing how cloning an `Rc` increases the +`strong_count` of references; `Weak` is a way to reference an `Rc` that +does not increment the `strong_count`: instead it increments the `weak_count` +of references to an `Rc`. When an `Rc` goes out of scope, the inner value will +get dropped if the `strong_count` is 0, even if the `weak_count` is not 0. To +be able to get the value from a `Weak`, we first have to upgrade it to an +`Option>` by using the `upgrade` method. The result of upgrading a +`Weak` will be `Some` if the `Rc` value has not been dropped yet, and `None` +if the `Rc` value has been dropped. Because `upgrade` returns an `Option`, we +know Rust will make sure we handle both the `Some` case and the `None` case and +we won't be trying to use an invalid pointer. -Instead of the list in Listing 15-14 where each element knows only about the -next element, let's say we want a list where the elements know about their next -element *and* their previous element. +Instead of the list in Listing 15-14 where each item knows only about the +next item, let's say we want a tree where the items know about their children +items *and* their parent items. -So in order to make it possible to create lists that point to each other but -not create reference cycles, in Listing 15-15, we're going to change our -definition of `List` again to hold a `Weak` instead of an `Rc`. +Let's start just with a struct named `Node` that holds its own `i32` value as +well as references to its children `Node` values: + +Filename: src/main.rs + +```rust +#[derive(Debug)] +struct Node { + value: i32, + children: RefCell>>, +} +``` + +We want to be able to have a `Node` own its children, and we also want to be +able to have variables own each node so we can access them directly. That's why +the items in the `Vec` are `Rc` values. We want to be able to modify what +nodes are another node's children, so that's why we have a `RefCell` in +`children` around the `Vec`. Now let's create one instance of `Node` named +`leaf` with the value 3 and no children, and another instance named `branch` +with the value 5 and `leaf` as one of its children:
Filename: src/main.rs ```rust -#[derive(Debug)] -struct Node { - value: T, - parent: RefCell>>, - children: RefCell>>>, -} - -impl Node { - fn parent(&self) -> Option>> { - self.parent.borrow().upgrade() - } -} - -use std::rc::{Rc, Weak}; -use std::cell::RefCell; - fn main() { let leaf = Rc::new(Node { - value: 0, - parent: RefCell::new(Weak::new()), - children: RefCell::new(vec![]), - }); - - let another_leaf = Rc::new(Node { - value: 10, - parent: RefCell::new(Weak::new()), + value: 3, children: RefCell::new(vec![]), }); let branch = Rc::new(Node { - value: 50, + value: 5, + children: RefCell::new(vec![leaf.clone()]), + }); +} +``` + +
+ +Listing 15-15: Creating a `leaf` node and a `branch` node where `branch` has +`leaf` as one of its children but `leaf` has no reference to `branch` + +
+
+ +The `Node` in `leaf` now has two owners: `leaf` and `branch`, since we clone +the `Rc` in `leaf` and store that in `branch`. The `Node` in `branch` knows +it's related to `leaf` since `branch` has a reference to `leaf` in +`branch.children`. However, `leaf` doesn't know that it's related to `branch`, +and we'd like `leaf` to know that `branch` is its parent. + +To do that, we're going to add a `parent` field to our `Node` struct +definition, but what should the type of `parent` be? We know it can't contain +an `Rc`, since `leaf.parent` would point to `branch` and `branch.children` +contains a pointer to `leaf`, which makes a reference cycle. Neither `leaf` nor +`branch` would get dropped since they would always refer to each other and +their reference counts would never be zero. + +So instead of `Rc`, we're going to make the type of `parent` use `Weak`, +specifically a `RefCell>`: + +Filename: src/main.rs + +```rust +#[derive(Debug)] +struct Node { + value: i32, + parent: RefCell>, + children: RefCell>>, +} +``` + +This way, a node will be able to refer to its parent node if it has one, +but it does not own its parent. A parent node will be dropped even if +it has child nodes referring to it, as long as it doesn't have a parent +node as well. Now let's update `main` to look like this: + +
+Filename: src/main.rs + +```rust +fn main() { + let leaf = Rc::new(Node { + value: 3, parent: RefCell::new(Weak::new()), - children: RefCell::new(vec![leaf.clone(), another_leaf.clone()]), + children: RefCell::new(vec![]), + }); + + println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); + + let branch = Rc::new(Node { + value: 5, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![leaf.clone()]), }); *leaf.parent.borrow_mut() = Rc::downgrade(&branch); - *another_leaf.parent.borrow_mut() = Rc::downgrade(&branch); - println!("leaf = {:?}", leaf); - println!("leaf parent = {:?}", leaf.parent()); - - println!("another_leaf = {:?}", another_leaf); - println!("another_leaf parent = {:?}", another_leaf.parent()); - - println!("branch = {:?}", branch); - println!("branch parent = {:?}", branch.parent()); - - { - let another_branch = Rc::new(Node { - value: 70, - parent: RefCell::new(Weak::new()), - children: RefCell::new(vec![branch.clone()]), - }); - - *branch.parent.borrow_mut() = Rc::downgrade(&another_branch); - - println!("leaf = {:?}", leaf); - println!("leaf parent = {:?}", leaf.parent()); - - println!("another_leaf = {:?}", another_leaf); - println!("another_leaf parent = {:?}", another_leaf.parent()); - - println!("branch = {:?}", branch); - println!("branch parent = {:?}", branch.parent()); - - println!("another_branch = {:?}", another_branch); - println!("another_branch parent = {:?}", another_branch.parent()); - - assert_eq!(2, Rc::strong_count(&leaf)); - assert_eq!(0, Rc::weak_count(&leaf)); - - assert_eq!(2, Rc::strong_count(&another_leaf)); - assert_eq!(0, Rc::weak_count(&another_leaf)); - - assert_eq!(2, Rc::strong_count(&branch)); - assert_eq!(2, Rc::weak_count(&branch)); - - assert_eq!(1, Rc::strong_count(&another_branch)); - assert_eq!(1, Rc::weak_count(&another_branch)); - } - - println!("leaf = {:?}", leaf); - println!("leaf parent = {:?}", leaf.parent()); - - println!("another_leaf = {:?}", another_leaf); - println!("another_leaf parent = {:?}", another_leaf.parent()); - - println!("branch = {:?}", branch); - println!("branch parent = {:?}", branch.parent()); - - assert_eq!(2, Rc::strong_count(&leaf)); - assert_eq!(0, Rc::weak_count(&leaf)); - - assert_eq!(2, Rc::strong_count(&another_leaf)); - assert_eq!(0, Rc::weak_count(&another_leaf)); - - assert_eq!(1, Rc::strong_count(&branch)); - assert_eq!(2, Rc::weak_count(&branch)); + println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); } ```
-Listing 15-15: TODO rework text around here, get some reviews on this example +Listing 15-16: A `leaf` node and a `branch` node where `leaf` has a `Weak` +reference to its parent, `branch`
-We've also modified the `tail` method: not only does it return `None` when -`self` is `Nil` and doesn't have a `tail`, it now also returns `None` if the -value that the `Weak` references has been dropped. The `upgrade` method on a -`Weak` value returns `Some` containing an `Rc` if the value has not yet been -dropped and `None` if the value has been dropped. +Creating the `leaf` node looks similar; since it starts out without a parent, +we create a new `Weak` reference instance. When we try to get a reference to +the parent of `leaf` by using the `upgrade` method, we'll get a `None` value, +as shown by the first `println!` that outputs: -TODO: is this bad software design, collapsing two cases that return `None` like this??? +```text +leaf parent = None +``` -To create `Weak` values, we call the `Rc::downgrade` associated function, -which takes an `&Rc` as an argument, and gives a `Weak` back. +Similarly, `branch` will also have a new `Weak` reference, since `branch` does +not have a parent node. We still make `leaf` be one of the children of +`branch`. Once we have a new `Node` instance in `branch`, we can modify `leaf` +to have a `Weak` reference to `branch` for its parent. We use the `borrow_mut` +method on the `RefCell` in the `parent` field of `leaf`, then we use the +`Rc::downgrade` function to create a `Weak` reference to `branch` from the `Rc` +in `branch.` -Listing 15-16 shows a `main` method where we're trying to create `a` and `b` -lists that point to each other, similarly to what we did in Listing 15-14, but -this time we won't have a reference cycle and the values will be dropped when -they go out of scope at the end of `main`: +When we print out the parent of `leaf` again, this time we'll get a `Some` +variant holding `branch`. Also notice we don't get a cycle printed out that +eventually ends in a stack overflow like we did in Listing 15-14: the `Weak` +references are just printed as `(Weak)`: + +```text +leaf parent = Some(Node { value: 5, parent: RefCell { value: (Weak) }, +children: RefCell { value: [Node { value: 3, parent: RefCell { value: (Weak) }, +children: RefCell { value: [] } }] } }) +``` + +The fact that we don't get infinite output (or at least until the stack +overflows) is one way we can see that we don't have a reference cycle in this +case. Another way we can tell is by looking at the values we get from calling +`Rc::strong_count` and `Rc::weak_count`. Let's create a new inner scope and +move the creation of `branch` in there, so that we can see what happens when +`branch` is created and then dropped when it goes out of scope:
+Filename: src/main.rs -```rust -# #[derive(Debug)] -# enum List { -# Cons(T, RefCell>>), -# Nil, -# } -# -# impl List { -# fn tail(&self) -> Option>> { -# match *self { -# Cons(_, ref n) => (&*n.borrow()).upgrade(), -# Nil => None, -# } -# } -# } -# -use List::{Cons, Nil}; -use std::rc::{Rc, Weak}; -use std::cell::RefCell; - +``` fn main() { - let nil = Rc::new(Nil); + let leaf = Rc::new(Node { + value: 3, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![]), + }); - let a = Rc::new(Cons(5, RefCell::new(Rc::downgrade(&nil)))); - - println!("a.tail() = {:?}", a.tail()); + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); { - let b = Rc::new(Cons(10, RefCell::new(Rc::downgrade(&a)))); + let branch = Rc::new(Node { + value: 5, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![leaf.clone()]), + }); + *leaf.parent.borrow_mut() = Rc::downgrade(&branch); - if let Cons(_, ref link) = *a { - *link.borrow_mut() = Rc::downgrade(&b); - } + println!( + "branch strong = {}, weak = {}", + Rc::strong_count(&branch), + Rc::weak_count(&branch), + ); - println!("a.tail() = {:?}", a.tail()); - println!("b.tail() = {:?}", b.tail()); + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); } - println!("a.tail() = {:?}", a.tail()); + println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); } ```
-Listing 15-16: Creating `List` values using weak references +Listing 15-17: Creating `branch` in an inner scope and examining strong and +weak reference counts of `leaf` and `branch`
-First, we create a variable for the `Rc` that holds the `Nil` value, so that -it's clearer to see that we call `Rc::downgrade` and pass a reference to `nil` -when we create `a`. At that point, we print out the value of `a.tail()` and we -can see that it's `Some(Nil)`. +Right after creating `leaf`, its strong count is 1 (for `leaf` itself) and its +weak count is 0. In the inner scope, after we create `branch` and associate +`leaf` and `branch`, `branch` will have a strong count of 1 (for `branch` +itself) and a weak count of 1 (for `leaf.parent` pointing to `branch` with a +`Weak`). `leaf` will have a strong count of 2, since `branch` now has a +clone the `Rc` of `leaf` stored in `branch.children`. `leaf` still has a weak +count of 0. -We've added an inner scope in order to demonstrate what happens when `b` goes -out of scope. In the inner scope, we create `b` that has a weak reference to -`a`, and then we modify `a` to have a weak reference to `b` instead of to -`nil`. At the end of the inner scope, we can see that `a` and `b` are pointing -to each other, but through weak references. +When the inner scope ends, `branch` goes out of scope, and its strong count +decreases to 0, so its `Node` gets dropped. The weak count of 1 from +`leaf.parent` has no bearing on whether `Node` gets dropped or not, so we don't +have a memory leak! -At the end of the inner scope, `b` goes out of scope. The value that the -`Rc` in `b` holds gets dropped, even though `a` still references it, because -the reference in `a` is a weak reference that doesn't count when Rust decides -whether the value in `b` should be dropped or not. At the end of `main` when we -print out `a.tail()` again, we can see that we now get a `None` value since the -value that the weak reference in `a` was pointing to has been dropped. Success! -We've broken the cycle. +If we try to access the parent of `leaf` after the end of the scope, we'll get +`None` again like we did before `leaf` had a parent. At the end of the program, +`leaf` has a strong count of 1 and a weak count of 0, since `leaf` is now the +only thing pointing to it again. -Add some `println!` statements at various places that display the values that -`Rc::strong_count` and `Rc::weak_count` return for `a` and `b` at different -points in this example to see which parts of the code increase or decrease the -strong or weak counts. - -If you're doing complex things with `Rc`s, you should investigate if it's -possible for you to have a cycle, and insert a `Weak` so that you don't -create cycles and leak memory. The specifics depend on exactly what you're -doing, but luckily, this isn't a Rust-specific idea; all of this translates -over to other reference counting libraries in other languages, so doing some -reading about it should help you. +All of the logic managing the counts and whether a value should be dropped or +not was managed by `Rc` and `Weak` and their implementations of the `Drop` +trait. By specifying that the relationship from a child to its parent should be +a `Weak` reference in the definition of `Node`, we're able to have parent +nodes point to child nodes and vice versa without creating a reference cycle +and memory leaks. ## Summary From 542013ad1a15b259b1d4e96fdcadb01f190d3508 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 16:32:44 -0500 Subject: [PATCH 34/42] See if we can get away with not editing chapter 4 --- src/ch15-02-deref.md | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/src/ch15-02-deref.md b/src/ch15-02-deref.md index 8916eba21..11a65157c 100644 --- a/src/ch15-02-deref.md +++ b/src/ch15-02-deref.md @@ -2,12 +2,15 @@ The first important smart pointer-related trait is `Deref`, which allows us to override `*`, the dereference operator (as opposed to the multiplication -operator). Overriding `*` for smart pointers makes accessing the data behind -the smart pointer convenient, and we'll talk about what we mean by convenient -in the next section about deref coercions. Remember using `*` when we talked -about references, like this: +operator or the glob operator). Overriding `*` for smart pointers makes +accessing the data behind the smart pointer convenient, and we'll talk about +what we mean by convenient when we get to deref coercions later in this section. -TODO: put this back in ch 4 +We briefly mentioned the dereference operator in Chapter 8, in the hash map +section titled "Update a Value Based on the Old Value". We had a mutable +reference, and we wanted to change the value that the reference was pointing +to. In order to do that, first we had to dereference the reference. Here's +another example using references to `i32` values: ```rust let mut x = 5; @@ -20,12 +23,20 @@ let mut x = 5; assert_eq!(6, x); ``` -We use `*y` to access the data that `y` refers to, rather than `y` itself, -which is a reference. +We use `*y` to access the data that the mutable reference in `y` refers to, +rather than the mutable reference itself. We can then modify that data, in this +case by adding 1. -END TODO +With references that aren't smart pointers, there's only one value that the +reference is pointing to, so the dereference operation is straightforward. +Smart pointers can also store metadata about the pointer or the data. When +dereferencing a smart pointer, we only want the data, not the metadata, since +dereferencing a regular reference only gives us data and not metadata. We want +to be able to use smart pointers in the same places that we can use regular +references. To enable that, we can override the behavior of the `*` operator by +implementing the `Deref` trait. -Listing 15-5 has an example of overloading `*` using `Deref` on a struct we've +Listing 15-5 has an example of overriding `*` using `Deref` on a struct we've defined to hold mp3 data and metadata. `Mp3` is, in a sense, a smart pointer: it owns the `Vec` data containing the audio. In addition, it holds some optional metadata, in this case the artist and title of the song in the audio @@ -166,8 +177,6 @@ so there is no run-time penalty for taking advantage of deref coercion. There's also a `DerefMut` trait for overriding `*` on `&mut T` for use in assignment in the same fashion that we use `Deref` to override `*` on `&T`s. -TODO: insert x/y example here - Rust does deref coercion when it finds types and trait implementations in three cases: From b13b292002d302d6471bf7c667f602e50b169fd9 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 16:45:10 -0500 Subject: [PATCH 35/42] Fixing spelling and tests --- dictionary.txt | 2 ++ src/ch15-06-reference-cycles.md | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/dictionary.txt b/dictionary.txt index 414fd805d..1400454f3 100644 --- a/dictionary.txt +++ b/dictionary.txt @@ -53,6 +53,7 @@ CStr CString ctrl Ctrl +CustomSmartPointer deallocated deallocating deallocation @@ -210,6 +211,7 @@ refactor refactoring refcell RefCell +RefMut repr retweet ripgrep diff --git a/src/ch15-06-reference-cycles.md b/src/ch15-06-reference-cycles.md index ace15083c..73ee90f6b 100644 --- a/src/ch15-06-reference-cycles.md +++ b/src/ch15-06-reference-cycles.md @@ -182,6 +182,9 @@ well as references to its children `Node` values: Filename: src/main.rs ```rust +use std::rc::Rc; +use std::cell::RefCell; + #[derive(Debug)] struct Node { value: i32, @@ -241,6 +244,9 @@ specifically a `RefCell>`: Filename: src/main.rs ```rust +use std::rc::{Rc, Weak}; +use std::cell::RefCell; + #[derive(Debug)] struct Node { value: i32, From 0e276540789a57d89cb4d59622e9ff020b04a88d Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 17:22:51 -0500 Subject: [PATCH 36/42] Infinite type illustration --- dot/trpl15-01.dot | 23 +++++++++++++++++++++++ src/img/trpl15-01.svg | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 dot/trpl15-01.dot create mode 100644 src/img/trpl15-01.svg diff --git a/dot/trpl15-01.dot b/dot/trpl15-01.dot new file mode 100644 index 000000000..217d6d09e --- /dev/null +++ b/dot/trpl15-01.dot @@ -0,0 +1,23 @@ +digraph { + rankdir=LR; + dpi=300.0; + node [shape="plaintext"]; + + table0[label=< + + +
Cons
i32 + + +
Cons
i32 + + +
Cons
i32 + + +
Cons
i32 + + +
Cons
i32∞
>]; +} + diff --git a/src/img/trpl15-01.svg b/src/img/trpl15-01.svg new file mode 100644 index 000000000..b87382552 --- /dev/null +++ b/src/img/trpl15-01.svg @@ -0,0 +1,42 @@ + + + + + + +%3 + + +table0 + +Cons + +i32 + + +Cons + +i32 + + +Cons + +i32 + + +Cons + +i32 + + +Cons + +i32 + +∞ + + + From a17e7caf2a9e5ee68a272960a1e67dcc2261af3a Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 17:40:18 -0500 Subject: [PATCH 37/42] Add a diagram for Cons with Box --- dot/trpl15-02.dot | 17 ++++++++++++++++ src/ch15-01-box.md | 46 +++++++++++++++++++++++++++++++++---------- src/img/trpl15-02.svg | 25 +++++++++++++++++++++++ 3 files changed, 78 insertions(+), 10 deletions(-) create mode 100644 dot/trpl15-02.dot create mode 100644 src/img/trpl15-02.svg diff --git a/dot/trpl15-02.dot b/dot/trpl15-02.dot new file mode 100644 index 000000000..bdd8b517a --- /dev/null +++ b/dot/trpl15-02.dot @@ -0,0 +1,17 @@ +digraph { + rankdir=LR; + dpi=300.0; + node [shape="plaintext"]; + + table0[label=< + + + +
Cons
i32 + + + +
Box
usize
+
>]; +} + diff --git a/src/ch15-01-box.md b/src/ch15-01-box.md index fe8bf1264..e7b6e7214 100644 --- a/src/ch15-01-box.md +++ b/src/ch15-01-box.md @@ -139,11 +139,23 @@ variant. The `Cons` variant holds a value of type `i32` and a value of type `List`, so `Cons` needs an amount of space equal to the size of an `i32` plus the size of a `List`. To figure out how much memory a `List` needs, it looks at its variants, starting with the `Cons` variant. The `Cons` variant holds a -value of type `i32` and a value of type `List`, and this continues infinitely. -Rust can't figure out how much space to allocate for recursively defined types, -so the compiler gives the error in Listing 15-3. +value of type `i32` and a value of type `List`, and this continues infinitely, +as shown in Figure 15-4. -The compiler did give a helpful suggestion in the error output: +
+ +Depiction of an infinite Cons list + +
+ +Figure 15-4: An infinite `List` consisting of infinite `Cons` variants + +
+
+ +Rust can't figure out how much space to allocate for recursively defined types, +so the compiler gives the error in Listing 15-3. The error did include this +helpful suggestion: ```text = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to @@ -154,7 +166,7 @@ Because a `Box` is a pointer, we always know how much space it needs: a pointer takes up a `usize` amount of space. The value of the `usize` will be the address of the heap data. The heap data can be any size, but the address to the start of that heap data will always fit in a `usize`. So if we change our -definition from Listing 15-2 to look like the definition here in Listing 15-4, +definition from Listing 15-2 to look like the definition here in Listing 15-5, and change `main` to use `Box::new` for the values inside the `Cons` variants like so: @@ -179,7 +191,7 @@ fn main() {
-Listing 15-4: Definition of `List` that uses `Box` in order to have a +Listing 15-5: Definition of `List` that uses `Box` in order to have a known size
@@ -191,10 +203,24 @@ variant. The `Cons` variant will need the size of `i32` plus the space to store a `usize`, since a box always has the size of a `usize`, no matter what it's pointing to. Then Rust looks at the `Nil` variant, which does not store a value, so `Nil` doesn't need any space. We've broken the infinite, recursive -chain by adding in a box. This is the main area where boxes are useful: -breaking up an infinite data structure so that the compiler can know what size -it is. We'll look at another case where Rust has data of unknown size in -Chapter 17 when we discuss trait objects. +chain by adding in a box. Figure 15-6 shows what the `Cons` variant looks like +now: + +
+ +Depiction of a finite Cons list + +
+ +Figure 15-6: A `List` that is not infinitely sized since `Cons` holds a `Box` + +
+
+ +This is the main area where boxes are useful: breaking up an infinite data +structure so that the compiler can know what size it is. We'll look at another +case where Rust has data of unknown size in Chapter 17 when we discuss trait +objects. Even though you won't be using boxes very often, they are a good way to understand the smart pointer pattern. Two of the aspects of `Box` that are diff --git a/src/img/trpl15-02.svg b/src/img/trpl15-02.svg new file mode 100644 index 000000000..5b869853f --- /dev/null +++ b/src/img/trpl15-02.svg @@ -0,0 +1,25 @@ + + + + + + +%3 + + +table0 + +Cons + +i32 + + +Box + +usize + + + From 07310e5fcdc862efd1acde98f84293e4e7c20933 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 18:12:30 -0500 Subject: [PATCH 38/42] Add more figures --- dot/trpl15-03.dot | 50 +++++++++++++++++++++++ src/ch15-02-deref.md | 4 +- src/ch15-03-drop.md | 10 ++--- src/ch15-04-rc.md | 31 ++++++++------ src/img/trpl15-03.svg | 94 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 169 insertions(+), 20 deletions(-) create mode 100644 dot/trpl15-03.dot create mode 100644 src/img/trpl15-03.svg diff --git a/dot/trpl15-03.dot b/dot/trpl15-03.dot new file mode 100644 index 000000000..5626de248 --- /dev/null +++ b/dot/trpl15-03.dot @@ -0,0 +1,50 @@ +digraph { + rankdir=LR; + dpi=300.0; + node [shape="plaintext"]; + + table4[label=< + +
b
>]; + + table5[label=< + +
3
>]; + + + table0[label=< + +
a
>]; + + table1[label=< + +
5
>]; + + table2[label=< + +
10
>]; + + table3[label=< + +
Nil
>]; + + + table6[label=< + +
c
>]; + + table7[label=< + +
4
>]; + + + edge[tailclip="false"]; + table0:ptr0:c -> table1:pte0; + table1:ptr1:c -> table2:pte1; + table2:ptr2:c -> table3:pte2; + table4:ptr4:c -> table5:pte4; + table5:ptr5:c -> table1:pte0; + table6:ptr6:c -> table7:pte6; + table7:ptr7:c -> table1:pte0; +} + diff --git a/src/ch15-02-deref.md b/src/ch15-02-deref.md index 11a65157c..47b35ed48 100644 --- a/src/ch15-02-deref.md +++ b/src/ch15-02-deref.md @@ -36,7 +36,7 @@ to be able to use smart pointers in the same places that we can use regular references. To enable that, we can override the behavior of the `*` operator by implementing the `Deref` trait. -Listing 15-5 has an example of overriding `*` using `Deref` on a struct we've +Listing 15-7 has an example of overriding `*` using `Deref` on a struct we've defined to hold mp3 data and metadata. `Mp3` is, in a sense, a smart pointer: it owns the `Vec` data containing the audio. In addition, it holds some optional metadata, in this case the artist and title of the song in the audio @@ -79,7 +79,7 @@ fn main() {
-Listing 15-5: An implementation of the `Deref` trait on a struct that holds mp3 +Listing 15-7: An implementation of the `Deref` trait on a struct that holds mp3 file data and metadata
diff --git a/src/ch15-03-drop.md b/src/ch15-03-drop.md index 220e6a24c..1fd16eddb 100644 --- a/src/ch15-03-drop.md +++ b/src/ch15-03-drop.md @@ -21,7 +21,7 @@ The way we specify code should be run when a value goes out of scope is by implementing the `Drop` trait. The `Drop` trait requires us to implement one method named `drop` that takes a mutable reference to `self`. -Listing 15-6 shows a `CustomSmartPointer` struct that doesn't actually do +Listing 15-8 shows a `CustomSmartPointer` struct that doesn't actually do anything, but we're printing out `CustomSmartPointer created.` right after we create an instance of the struct and `Dropping CustomSmartPointer!` when the instance goes out of scope so that we can see when each piece of code gets run. @@ -51,7 +51,7 @@ fn main() {
-Listing 15-6: A `CustomSmartPointer` struct that implements the `Drop` trait, +Listing 15-8: A `CustomSmartPointer` struct that implements the `Drop` trait, where we could put code that would clean up after the `CustomSmartPointer`.
@@ -82,7 +82,7 @@ trait is that it's taken care of automatically for us. We'll see an example of a case when we'll need to drop a value earlier than when it goes out of scope in Chapter 16 when we're talking about concurrency. For now, let's just see that it's possible, and `std::mem::drop` is in the prelude so we can just call -`drop` as shown in Listing 15-7: +`drop` as shown in Listing 15-9:
@@ -97,7 +97,7 @@ fn main() {
-Listing 15-7: Calling `std::mem::drop` to explicitly drop a value before it +Listing 15-9: Calling `std::mem::drop` to explicitly drop a value before it goes out of scope
@@ -114,7 +114,7 @@ Wait for it... ``` Note that we aren't allowed to call the `drop` method that we defined directly: -if we replaced `drop(c)` in Listing 15-7 with `c.drop()`, we'll get a compiler +if we replaced `drop(c)` in Listing 15-9 with `c.drop()`, we'll get a compiler error that says `explicit destructor calls not allowed`. We're not allowed to call `Drop::drop` directly because when Rust inserts its call to `Drop::drop` automatically when the value goes out of scope, then the value would get diff --git a/src/ch15-04-rc.md b/src/ch15-04-rc.md index 743a7276b..8e3fcf4e8 100644 --- a/src/ch15-04-rc.md +++ b/src/ch15-04-rc.md @@ -29,23 +29,28 @@ you'll get a compile-time error. ### Using `Rc` to Share Data -Let's return to our cons list example from Listing 15-4. In Listing 15-8, we're +Let's return to our cons list example from Listing 15-5. In Listing 15-11, we're going to try to use `List` as we defined it using `Box`. First we'll create one list instance that contains 5 and then 10. Next, we want to create two more lists: one that starts with 3 and continues on to our first list containing 5 and 10, then another list that starts with 4 and *also* continues on to our first list containing 5 and 10. In other words, we want two lists that both share ownership of the third list, which conceptually will be something like -this: +Figure 15-10: -```text -b -> 3 ---v -a ------> 5 -> 10 -> Nil -c -> 4 ---^ -``` +
+ +Two lists that share ownership of a third list + +
+ +Figure 15-10: Two lists, `b` and `c`, sharing ownership of a third list, `a` + +
+
Trying to implement this using our definition of `List` with `Box` won't -work: +work, as shown in Listing 15-11:
Filename: src/main.rs @@ -69,7 +74,7 @@ fn main() {
-Listing 15-8: Having two lists using `Box` that try to share ownership of a +Listing 15-11: Having two lists using `Box` that try to share ownership of a third list won't work
@@ -100,7 +105,7 @@ a list such that every element lives at least as long as the list itself. Otherwise, the borrow checker won't even let us compile the code. Instead, we can change our definition of `List` to use `Rc` instead of -`Box` as shown here in Listing 15-9: +`Box` as shown here in Listing 15-12:
Filename: src/main.rs @@ -123,7 +128,7 @@ fn main() {
-Listing 15-9: A definition of `List` that uses `Rc` +Listing 15-12: A definition of `List` that uses `Rc`
@@ -137,7 +142,7 @@ prelude. In `main`, we create the list holding 5 and 10 and store it in a new We've seen the `clone` method previously, where we used it for making a complete copy of some data. With `Rc`, though, it doesn't make a full copy. `Rc` holds a *reference count*, that is, a count of how many clones exist. -Let's change `main` as shown in Listing 15-10 to have an inner scope around +Let's change `main` as shown in Listing 15-13 to have an inner scope around where we create `c`, and to print out the results of the `Rc::strong_count` associated function at various points. `Rc::strong_count` returns the reference count of the `Rc` value we pass to it, and we'll talk about why this function @@ -171,7 +176,7 @@ fn main() {
-Listing 15-10: Printing out the reference count +Listing 15-13: Printing out the reference count
diff --git a/src/img/trpl15-03.svg b/src/img/trpl15-03.svg new file mode 100644 index 000000000..e26024f6b --- /dev/null +++ b/src/img/trpl15-03.svg @@ -0,0 +1,94 @@ + + + + + + +%3 + + +table4 +b + + +table5 + +3 + +   + + +table4:ptr4:c->table5:pte4 + + + + +table1 + +5 + +   + + +table5:ptr5:c->table1:pte0 + + + + +table0 +a + + +table0:ptr0:c->table1:pte0 + + + + +table2 + +10 + +   + + +table1:ptr1:c->table2:pte1 + + + + +table3 + +Nil + + +table2:ptr2:c->table3:pte2 + + + + +table6 +c + + +table7 + +4 + +   + + +table6:ptr6:c->table7:pte6 + + + + +table7:ptr7:c->table1:pte0 + + + + + From 87609b12b849aa8978869b3dbaf5a5ad7e4e41b3 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 20:09:19 -0500 Subject: [PATCH 39/42] graphviz is terrible --- dot/trpl15-04.dot | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 dot/trpl15-04.dot diff --git a/dot/trpl15-04.dot b/dot/trpl15-04.dot new file mode 100644 index 000000000..7b7401608 --- /dev/null +++ b/dot/trpl15-04.dot @@ -0,0 +1,35 @@ +digraph { + rankdir="LR"; + dpi=300.0; + node [shape="plaintext"]; + + table0[label=< + +
a
>]; + + table1[label=< + +
5
>]; + + + table3[label=< + +
10
>]; + + + table2[label=< + +
b
>]; + + + edge[tailclip="false"]; + table0:ptr0:c -> table1:pte0; + table1:ptr1:c -> table2:pte1; + table2:ptr2:c -> table3:pte2; + table3:ptr3:c -> table0:pte3; + + { rank="same"; table3; table0; } + { rank="same"; table1; table2; } + +} + From 5f6113d586f5e9653052033908d27516f88388fc Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 20:40:21 -0500 Subject: [PATCH 40/42] wrong way arrow --- dot/trpl15-04.dot | 20 +++++++-------- src/img/trpl15-04.svg | 60 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 11 deletions(-) create mode 100644 src/img/trpl15-04.svg diff --git a/dot/trpl15-04.dot b/dot/trpl15-04.dot index 7b7401608..3e653fafc 100644 --- a/dot/trpl15-04.dot +++ b/dot/trpl15-04.dot @@ -4,32 +4,30 @@ digraph { node [shape="plaintext"]; table0[label=< - +
a
a
>]; table1[label=<
5
>]; + table2[label=< + +
b
>]; table3[label=< - +
10
10
>]; - - table2[label=< - -
b
>]; - - edge[tailclip="false"]; table0:ptr0:c -> table1:pte0; table1:ptr1:c -> table2:pte1; - table2:ptr2:c -> table3:pte2; - table3:ptr3:c -> table0:pte3; + table3:ptr2 -> table2:pte2 [ dir="back" ]; + + table0:ptr3 -> table3:pte3:c; - { rank="same"; table3; table0; } { rank="same"; table1; table2; } + { rank="same"; table0; table3; } } diff --git a/src/img/trpl15-04.svg b/src/img/trpl15-04.svg new file mode 100644 index 000000000..4a36497bb --- /dev/null +++ b/src/img/trpl15-04.svg @@ -0,0 +1,60 @@ + + + + + + +%3 + + +table0 + +a + + + +table1 + +5 + +   + + +table0:ptr0:c->table1:pte0 + + + + +table3 + +10 + +   + + +table0:ptr3->table3:pte3:c + + + + +table2 + +b + + + +table1:ptr1:c->table2:pte1 + + + + +table3:ptr2->table2:pte2 + + + + + From 3bfc407e6efcc64e08b8c62cdbaaee0ec1212e9d Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 20:54:26 -0500 Subject: [PATCH 41/42] halp can't get arrow pointing the way i want I cannot for the life of me get the arrow currently pointing from a -> 10 to point from 10 -> a instead, dir=back has no effect, changing the order makes the whole graph go kablooey, i even tried hand-editing the svg and i cannot --- dot/trpl15-04.dot | 1 - src/img/trpl15-04.svg | 4 ---- 2 files changed, 5 deletions(-) diff --git a/dot/trpl15-04.dot b/dot/trpl15-04.dot index 3e653fafc..d016cc8ab 100644 --- a/dot/trpl15-04.dot +++ b/dot/trpl15-04.dot @@ -23,7 +23,6 @@ digraph { table0:ptr0:c -> table1:pte0; table1:ptr1:c -> table2:pte1; table3:ptr2 -> table2:pte2 [ dir="back" ]; - table0:ptr3 -> table3:pte3:c; { rank="same"; table1; table2; } diff --git a/src/img/trpl15-04.svg b/src/img/trpl15-04.svg index 4a36497bb..dc973518e 100644 --- a/src/img/trpl15-04.svg +++ b/src/img/trpl15-04.svg @@ -12,9 +12,7 @@ xmlns:xlink="http://www.w3.org/1999/xlink"> table0 - a - table1 @@ -42,9 +40,7 @@ xmlns:xlink="http://www.w3.org/1999/xlink"> table2 - b - table1:ptr1:c->table2:pte1 From 364ff83e64848b06ed21b47a36027131f9b62cdf Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Thu, 2 Mar 2017 20:59:48 -0500 Subject: [PATCH 42/42] more diagrams --- src/ch15-01-box.md | 4 +-- src/ch15-05-interior-mutability.md | 12 ++++---- src/ch15-06-reference-cycles.md | 47 +++++++++++++++++------------- src/img/trpl15-04.svg | 2 +- 4 files changed, 36 insertions(+), 29 deletions(-) diff --git a/src/ch15-01-box.md b/src/ch15-01-box.md index e7b6e7214..14c5533bb 100644 --- a/src/ch15-01-box.md +++ b/src/ch15-01-box.md @@ -144,7 +144,7 @@ as shown in Figure 15-4.
-Depiction of an infinite Cons list +An infinite Cons list
@@ -208,7 +208,7 @@ now:
-Depiction of a finite Cons list +A finite Cons list
diff --git a/src/ch15-05-interior-mutability.md b/src/ch15-05-interior-mutability.md index d27eb69fe..a4ade4ae8 100644 --- a/src/ch15-05-interior-mutability.md +++ b/src/ch15-05-interior-mutability.md @@ -58,7 +58,7 @@ treat them as if they're regular references. `Ref` and `RefMut` track the borrows dynamically, and their implementation of `Drop` releases the borrow dynamically. -Listing 15-11 shows what it looks like to use `RefCell` with functions that +Listing 15-14 shows what it looks like to use `RefCell` with functions that borrow their parameters immutably and mutably. Note that the `data` variable is declared as immutable with `let data` rather than `let mut data`, yet `a_fn_that_mutably_borrows` is allowed to borrow the data mutably and make @@ -92,7 +92,7 @@ fn main() {
-Listing 15-11: Using `RefCell`, `borrow`, and `borrow_mut` +Listing 15-14: Using `RefCell`, `borrow`, and `borrow_mut`
@@ -184,8 +184,8 @@ So why would we choose to make the tradeoffs that using `RefCell` involves? Well, remember when we said that `Rc` only lets you have an immutable reference to `T`? Given that `RefCell` is immutable, but has interior mutability, we can combine `Rc` and `RefCell` to get a type that's both -reference counted and mutable. Listing 15-12 shows an example of how to do -that, again going back to our cons list from Listing 15-9. In this example, +reference counted and mutable. Listing 15-15 shows an example of how to do +that, again going back to our cons list from Listing 15-5. In this example, instead of storing `i32` values in the cons list, we'll be storing `Rc>` values. We want to store that type so that we can have an owner of the value that's not part of the list (the multiple owners @@ -225,7 +225,7 @@ fn main() {
-Listing 15-12: Using `Rc>` to create a `List` that we can mutate +Listing 15-15: Using `Rc>` to create a `List` that we can mutate
@@ -236,7 +236,7 @@ directly later. Then we create a `List` in `a` that has a `Cons` variant that holds `value`, and `value` needs to be cloned since we want `value` to also have ownership in addition to `a`. Then we wrap `a` in an `Rc` so that we can create lists `b` and `c` that start differently but both refer to `a`, -similarly to what we did in Listing 15-9. +similarly to what we did in Listing 15-12. Once we have the lists in `shared_list`, `b`, and `c` created, then we add 10 to the 5 in `value` by dereferencing the `Rc` and calling `borrow_mut` on diff --git a/src/ch15-06-reference-cycles.md b/src/ch15-06-reference-cycles.md index 73ee90f6b..76009a2aa 100644 --- a/src/ch15-06-reference-cycles.md +++ b/src/ch15-06-reference-cycles.md @@ -13,8 +13,8 @@ reference count of each item in the cycle will never reach 0, and the values will never be dropped. Let's take a look at how that might happen and how to prevent it. -In Listing 15-13, we're going to use another variation of the `List` definition -from Listing 15-12. We're going back to storing an `i32` value as the first +In Listing 15-16, we're going to use another variation of the `List` definition +from Listing 15-5. We're going back to storing an `i32` value as the first element in the `Cons` variant. The second element in the `Cons` variant is now `RefCell>`: instead of being able to modify the `i32` value this time, we want to be able to modify which `List` a `Cons` variant is pointing to. @@ -46,15 +46,13 @@ impl List {
-Listing 15-13: A cons list definition that holds a `RefCell` so that we can +Listing 15-16: A cons list definition that holds a `RefCell` so that we can modify what a `Cons` variant is referring to
-TODO: insert diagram showing the "shape" of the `Cons` variant? - -Next, in Listing 15-14, we're going to create a `List` value in the variable +Next, in Listing 15-17, we're going to create a `List` value in the variable `a` that initially is a list of `5, Nil`. Then we'll create a `List` value in the variable `b` that is a list of the value 10 and then points to the list in `a`. Finally, we'll modify `a` so that it points to `b` instead of `Nil`, which @@ -111,7 +109,7 @@ fn main() {
-Listing 15-14: Creating a reference cycle of two `List` values pointing to +Listing 15-17: Creating a reference cycle of two `List` values pointing to each other
@@ -120,9 +118,18 @@ each other We use the `tail` method to get a reference to the `RefCell` in `a`, which we put in the variable `link`. Then we use the `borrow_mut` method on the `RefCell` to change the value inside from an `Rc` that holds a `Nil` value to -the `Rc` in `b`. We've created a reference cycle that looks like: +the `Rc` in `b`. We've created a reference cycle that looks like Figure 15-18: -TODO: insert diagram showing b and a pointing to each other +
+ +Reference cycle of lists + +
+ +Figure 15-18: A reference cycle of lists `a` and `b` pointing to each other + +
+
If you uncomment the last `println!`, Rust will try and print this cycle out with `a` pointing to `b` pointing to `a` and so forth until it overflows the @@ -172,7 +179,7 @@ if the `Rc` value has been dropped. Because `upgrade` returns an `Option`, we know Rust will make sure we handle both the `Some` case and the `None` case and we won't be trying to use an invalid pointer. -Instead of the list in Listing 15-14 where each item knows only about the +Instead of the list in Listing 15-17 where each item knows only about the next item, let's say we want a tree where the items know about their children items *and* their parent items. @@ -196,9 +203,9 @@ We want to be able to have a `Node` own its children, and we also want to be able to have variables own each node so we can access them directly. That's why the items in the `Vec` are `Rc` values. We want to be able to modify what nodes are another node's children, so that's why we have a `RefCell` in -`children` around the `Vec`. Now let's create one instance of `Node` named -`leaf` with the value 3 and no children, and another instance named `branch` -with the value 5 and `leaf` as one of its children: +`children` around the `Vec`. In Listing 15-19, let's create one instance of +`Node` named `leaf` with the value 3 and no children, and another instance +named `branch` with the value 5 and `leaf` as one of its children:
Filename: src/main.rs @@ -219,7 +226,7 @@ fn main() {
-Listing 15-15: Creating a `leaf` node and a `branch` node where `branch` has +Listing 15-19: Creating a `leaf` node and a `branch` node where `branch` has `leaf` as one of its children but `leaf` has no reference to `branch`
@@ -258,7 +265,7 @@ struct Node { This way, a node will be able to refer to its parent node if it has one, but it does not own its parent. A parent node will be dropped even if it has child nodes referring to it, as long as it doesn't have a parent -node as well. Now let's update `main` to look like this: +node as well. Now let's update `main` to look like Listing 15-20:
Filename: src/main.rs @@ -287,7 +294,7 @@ fn main() {
-Listing 15-16: A `leaf` node and a `branch` node where `leaf` has a `Weak` +Listing 15-20: A `leaf` node and a `branch` node where `leaf` has a `Weak` reference to its parent, `branch`
@@ -324,9 +331,9 @@ children: RefCell { value: [] } }] } }) The fact that we don't get infinite output (or at least until the stack overflows) is one way we can see that we don't have a reference cycle in this case. Another way we can tell is by looking at the values we get from calling -`Rc::strong_count` and `Rc::weak_count`. Let's create a new inner scope and -move the creation of `branch` in there, so that we can see what happens when -`branch` is created and then dropped when it goes out of scope: +`Rc::strong_count` and `Rc::weak_count`. In Listing 15-21, let's create a new +inner scope and move the creation of `branch` in there, so that we can see what +happens when `branch` is created and then dropped when it goes out of scope:
Filename: src/main.rs @@ -377,7 +384,7 @@ fn main() {
-Listing 15-17: Creating `branch` in an inner scope and examining strong and +Listing 15-21: Creating `branch` in an inner scope and examining strong and weak reference counts of `leaf` and `branch`
diff --git a/src/img/trpl15-04.svg b/src/img/trpl15-04.svg index dc973518e..648f55195 100644 --- a/src/img/trpl15-04.svg +++ b/src/img/trpl15-04.svg @@ -5,7 +5,7 @@ --> %3