finished ch15.4
Some checks failed
Test Gitea Actions / first (push) Successful in 14s
Test Gitea Actions / check-code (push) Failing after 14s
Test Gitea Actions / test (push) Has been skipped
Test Gitea Actions / documentation-check (push) Has been skipped

This commit is contained in:
darkicewolf50 2025-03-05 17:07:24 -07:00
parent 0052658af0
commit 90ffa5d8a5
5 changed files with 249 additions and 25 deletions

View File

@ -27,30 +27,40 @@
"state": { "state": {
"type": "markdown", "type": "markdown",
"state": { "state": {
"file": "Tests.md", "file": "Smart Pointers.md",
"mode": "source", "mode": "source",
"source": false "source": false
}, },
"icon": "lucide-file", "icon": "lucide-file",
"title": "Tests" "title": "Smart Pointers"
} }
}, },
{ {
"id": "ec34d2df2728a299", "id": "7615e7dc6a30893a",
"type": "leaf", "type": "leaf",
"state": { "state": {
"type": "markdown", "type": "markdown",
"state": { "state": {
"file": "minigrep/README.md", "file": "Reference Counter Smart Pointer.md",
"mode": "source", "mode": "source",
"source": false "source": false
}, },
"icon": "lucide-file", "icon": "lucide-file",
"title": "README" "title": "Reference Counter Smart Pointer"
}
},
{
"id": "6ed9f182aa3d5f3e",
"type": "leaf",
"state": {
"type": "graph",
"state": {},
"icon": "lucide-git-fork",
"title": "Graph view"
} }
} }
], ],
"currentTab": 2 "currentTab": 3
} }
], ],
"direction": "vertical" "direction": "vertical"
@ -193,11 +203,18 @@
"command-palette:Open command palette": false "command-palette:Open command palette": false
} }
}, },
"active": "ec34d2df2728a299", "active": "6ed9f182aa3d5f3e",
"lastOpenFiles": [ "lastOpenFiles": [
"Writing_Tests.md", "Reference Counter Smart Pointer.md",
"Smart Pointers.md",
"Ref Cell Mutability.md",
"The Performance Closures and Iterators.md",
"Improving The IO Project.md",
"Tests.md", "Tests.md",
"The Preformance Closures and Iterators.md",
"minigrep/README.md", "minigrep/README.md",
"Project Organization.md",
"Writing_Tests.md",
"minigrep/src/lib.rs", "minigrep/src/lib.rs",
"Test_Organization.md", "Test_Organization.md",
"Test Controls.md", "Test Controls.md",
@ -215,13 +232,6 @@
"Data Types.md", "Data Types.md",
"Enums.md", "Enums.md",
"Error Handling.md", "Error Handling.md",
"Hash.md",
"ownership.md",
"Packages.md",
"Paths.md",
"Primitives.md",
"Project Organization.md",
"README.md",
"does_not_compile.svg", "does_not_compile.svg",
"Untitled.canvas", "Untitled.canvas",
"Good and Bad Code/Commenting Pratices", "Good and Bad Code/Commenting Pratices",

View File

@ -209,4 +209,4 @@ Instead of fiddling with various bits of looping and building new vectors, the c
This abraction takes away some of the commonplace code so it is easier to see the concepts that are unique to this code, such as the filtering condition each element in the iteraor must pass. This abraction takes away some of the commonplace code so it is easier to see the concepts that are unique to this code, such as the filtering condition each element in the iteraor must pass.
You may think that the low level low will be but lets talk about performance [here](./The%20preformance%20Closures%20and%20Iterators.md). You may think that the low level low will be but lets talk about performance [here](./The%20Performance%20Closures%20and%20Iterators.md).

1
Ref Cell Mutability.md Normal file
View File

@ -0,0 +1 @@
# `RefCell<T>` and the Interior Mutability Pattern

View File

@ -1 +1,214 @@
# `RC<T>`, the Reference Counted Smart Pointer # `RC<T>`, the Reference Counted Smart Pointer
In the majority of times ownership is clear. You always know which variable owns a value.
There are cases when a single value might have multiple owners.
An example of this includes in graph data structures, multiple edges might point to the same node, and that node is conceptually owned by all of the edges that point to it.
A node shouldn't be cleaned up unless it doesn't have any edges pointing to it and so has no owners.
You must explicitly enable multiple ownership by using the Rust type `Rc<T>`, this is a abbreviation for *reference counting*.
This type keeps track of the number of references to a value to determine whether or not the value is still in use.
If there are no references to a value, then the value can be cleaned up without any references becoming invalid.
`Rc<T>` can be pictured as a TV in a family room.
When one person enters to watch the TV, they turn it on.
Others can come into the room and watch the TV.
When the last person leaves the room, they turn it off because it is no longer being used.
If someone turns off the TV while others are still watching it, there would be uproar from the remaining TV watchers.
`Rc<T>` type is used when we want to allocate some data on the heap for multiple parts of our program to read.
We can't determine at compile time which part will finish using the data last.
If we knew which part would finished last, we could just make that part the data's owner and the normal ownership rules enforced at compile time would take effect.
Note that `Rc<T>` is only for use in single-threaded cases.
We discuss later how to do reference counting in multithreaded programs.
## Using `Rc<T>` to Share Data
Lets use the cons list again to exemplify why to use a `Rc<T>`.
Recall that we previously defined it using `Box<T>`.
Now we will create two lists that both share ownership of a third list.
Here is a graph of what it would look like
<img src="https://doc.rust-lang.org/book/img/trpl15-03.svg" />
Here we create a list `a` that contains 5 then 10.
We then create two more lists
- `b` that starts with 3
- `c` that starts with 4
Both `b` and `c` will continue on to the first `a` list containing 5 and 10.
Both lists will share the first list containing 5 and 10.
Trying to implement this with our definition of `List` with `Box<T>` will not work nor compile
```rust
enum List {
Cons(i32, Box<List>),
Nil,
}
use crate::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));
}
```
When we try to compile this code we get this error
```
$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
error[E0382]: use of moved value: `a`
--> src/main.rs:11:30
|
9 | let a = Cons(5, Box::new(Cons(10, Box::new(Nil))));
| - move occurs because `a` has type `List`, which does not implement the `Copy` trait
10 | let b = Cons(3, Box::new(a));
| - value moved here
11 | let c = Cons(4, Box::new(a));
| ^ value used here after move
For more information about this error, try `rustc --explain E0382`.
error: could not compile `cons-list` (bin "cons-list") due to 1 previous error
```
The `Cons` variants own the data they hold so when we create the `b` list
`a` is moved into `b` and `b` owns `a`.
We could change the definition of `Cons` to hold a reference instead. We would then have to specify lifetime parameters.
Then by specifying lifetime parameters we would be specifying that every element in the list will live at least as long as the entire list.
This would be the case for the example above, but not in every scenario.
Instead we will change our definition of `List` to use `Rc<T>` in place of `Box<T>`.
Each `Cons` variant will now hold a value and an `Rc<T>` pointing to a `List`.
Now when we create `b`, instead of taking ownership of `a`.
We will clone the `Rc<List>` that `a` is holding, this increases the number of references from 1 -> 2 and letting `a` and `b` share ownership of the data in that `Rc<List>`.
Next we will clone `a` when creating `c`, increasing again the number of references form 2 -> 3.
Every time we call `Rc::clone`, the references count to the data within the `Rc<List>` will increase, and the data will not be cleaned up unless there are zero references to it.
```rust
enum List {
Cons(i32, Rc<List>),
Nil,
}
use crate::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, Rc::clone(&a));
let c = Cons(4, Rc::clone(&a));
}
```
We also need to add a `use` statement to bring `Rc<T>` into scope because it is not in the prelude.
Now in main we create the list holding 5 and 10 and store it in a new `Rc<List>` in `a`.
Then we create a `b` and `c`, we call the `Rc::clone` function and pass a reference to the `Rc<List>` in `a` as an arg.
We could have used `a.clone()` rather than `Rc::clone(&a)`.
It is convention in Rust to use `Rc::clone` in this case.
The implementation of `Rc::clone` doesn't make a deep copy of all data, this is unlike most tpyes' implementations of `clone`.
The call to `Rc::clone` only increments the reference count, this doesn't take much time.
Deep copies take much more time than a shallow copy.
By using `Rc::clone` for reference counting, we can visually distinguish between the deep-copy kinds of clines and the kinds of clones that increase the reference count.
When looking for performance problems in the code, we only need to consider the deep copy clones and can disregard class to `Rc::clone`
## Cloning an `Rc<T>` Increases the Reference Count
We will now change the example above to see the reference counts changing as we create and drop references to the `Rc<List>` in `a`
Here we changed it so that there is an inner scope around list `c`.
This is used so that we can see a difference when dropping `c`
```rust
enum List {
Cons(i32, Rc<List>),
Nil,
}
use crate::List::{Cons, Nil};
use std::rc::Rc;
fn main() {
let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
println!("count after creating a = {}", Rc::strong_count(&a));
let b = Cons(3, Rc::clone(&a));
println!("count after creating b = {}", Rc::strong_count(&a));
{
let c = Cons(4, Rc::clone(&a));
println!("count after creating c = {}", Rc::strong_count(&a));
}
println!("count after c goes out of scope = {}", Rc::strong_count(&a));
}
```
At each point in the program where the ref count changes we print out the count so that we can see it.
We do this by calling the `Rc::strong_count` function.
This is named `string_count` rather than `count` because the `Rc<T>` type also has a `weak_count`.
We will see `weak_count` later.
Here is the output
```
$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.45s
Running `target/debug/cons-list`
count after creating a = 1
count after creating b = 2
count after creating c = 3
count after c goes out of scope = 2
```
We cam see that the `a` of type `Rc<List>` has an initial count of 1.
Then each time we call `clone`, it goes up by 1.
When `c` goes out of scope, the count goes down by 1
We don't have to call a function to decrease the reference count like how we have to call `Rc::clone` to increase the ref count.
The implementation of the `Drop` trait decreases the ref count automatically when an `Rc<T>` value goes out of scope.
In this example we can't see what happens when `b` and `a` goes out of scope at the end of `main`, when the count is 0.
The `Rc<List>` is cleaned up completely.
Using `Rc<T>` allows a single value to have multiple owners, and the count ensures that the value remains valid as long as any of the owners still exist.
Using immutable references `Rc<T>` allows you to share data between multiple parts of your program for read only.
If `Rc<T>` allowed for multiple mutable references, you have the possibility of violating borrowing rules.
Multiple mutable borrows to the same place can cause data races and inconsistencies. [Section Reference Here](./ownership.md)
Being able to mutate data is very useful.
The nest section will the interior mutability pattern and the `RefCell<T>` type that you can use in conjunction with an `Rc<T>` to work with this immutability restriction.
It can be found [here](./Ref%20Cell%20Mutability.md).

View File

@ -9,7 +9,7 @@ References are indicated by the `&` symbol and borrow the value they point to.
They don't have any additional or special capabilities other than referring to data and have no overhead. They don't have any additional or special capabilities other than referring to data and have no overhead.
*Smart pointers* are data structures that act like a pointer but also have addtional metadata and capabilities. *Smart pointers* are data structures that act like a pointer but also have additional metadata and capabilities.
This idea of smart pointers is not unique to Rust. This idea of smart pointers is not unique to Rust.
@ -25,7 +25,7 @@ With the concept of ownership and borrowing in Rust it has an additional differe
While references only borrow data, in many cases, smart pointers *own* the data they point to. While references only borrow data, in many cases, smart pointers *own* the data they point to.
Even though we havent called them smart pinters before we have already interacted with a few smart pointers in previous chapters. Even though we haven't called them smart pointers before we have already interacted with a few smart pointers in previous chapters.
This includes `String` and `Vec<T>`. This includes `String` and `Vec<T>`.
@ -33,7 +33,7 @@ Both of these types count as smart pointers because they own some memory and all
They both contain metadata and extra capabilities or guarantees. They both contain metadata and extra capabilities or guarantees.
As an example `String` stores its capacity as metadata and has the extra ability to enusre its data will always be valid UTF-8. As an example `String` stores its capacity as metadata and has the extra ability to ensure its data will always be valid UTF-8.
Smart pointers are usually implemented using structs. Smart pointers are usually implemented using structs.
@ -43,17 +43,17 @@ The `Deref` trait allows an instance of the smart pointer struct to behave like
The `Drop` trait allows you to customize the code that is run when an instance of the smart pointer goes out of scope. [Section Link Here](./Drop%20Trait.md) The `Drop` trait allows you to customize the code that is run when an instance of the smart pointer goes out of scope. [Section Link Here](./Drop%20Trait.md)
We will go over both traits and demonstrate why they are improtant to smart pointers. We will go over both traits and demonstrate why they are important to smart pointers.
Given that the smart pointer pattern is a general design used often in Rust, we won't ocver every existing smart pointer. Given that the smart pointer pattern is a general design used often in Rust, we won't cover every existing smart pointer.
Many libraries have thier own smart pointers, and you can even write your own. Many libraries have their own smart pointers, and you can even write your own.
The ones we will cover are the most common smart pointers in the std library: The ones we will cover are the most common smart pointers in the std library:
- [`Box<T>` for allocating values on the heap](./Using%20Box%20on%20the%20Heap.md) - [`Box<T>` for allocating values on the heap](./Using%20Box%20on%20the%20Heap.md)
- `Rc<T>`, a reference counting type that enables multiple ownership [Section Link Here](./Reference%20Counter%20Smart%20Pointer.md) - `Rc<T>`, a reference counting type that enables multiple ownership [Section Link Here](./Reference%20Counter%20Smart%20Pointer.md)
- `Ref<T>` and `RefMut<T>` this is accessed through `RefCell<T>`, a type that enforces the borrowing rules at runtime instead of compile time - `Ref<T>` and `RefMut<T>` this is accessed through `RefCell<T>`, a type that enforces the borrowing rules at runtime instead of compile time [Section Link Here](./Ref%20Cell%20Mutability.md)
In additon we will also cover *interior mutability* patter where an immutable tpye exposes an API for mutating an interior value. In addition we will also cover *interior mutability* patter where an immutable type exposes an API for mutating an interior value.
As well discuss *reference cycles*; how they can leak memory and how to prevent them. As well discuss *reference cycles*; how they can leak memory and how to prevent them.