1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-01-10 00:44:21 +02:00

Add examples of the borrow checker catching errors (#2000)

I think it'd be helpful to actually demonstrate to students how the
"sharing XOR mutability" rule actually prevents errors in practice,
since right now we explain the rule but don't give much context as to
why the rule is important.
This commit is contained in:
Nicole L 2024-04-19 07:19:06 -07:00 committed by GitHub
parent 59d63a6e89
commit 0c23d817e5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 38 additions and 0 deletions

View File

@ -150,6 +150,7 @@
- [Borrowing](borrowing.md)
- [Borrowing a Value](borrowing/shared.md)
- [Borrow Checking](borrowing/borrowck.md)
- [Borrow Errors](borrowing/examples.md)
- [Interior Mutability](borrowing/interior-mutability.md)
- [Exercise: Health Statistics](borrowing/exercise.md)
- [Solution](borrowing/solution.md)

37
src/borrowing/examples.md Normal file
View File

@ -0,0 +1,37 @@
---
minutes: 3
---
# Borrow Errors
As a concrete example of how these borrowing rules prevent memory errors,
consider the case of modifying a collection while there are references to its
elements:
```rust,editable,compile_fail
fn main() {
let mut vec = vec![1, 2, 3, 4, 5];
let elem = &vec[2];
vec.push(6);
println!("{elem}");
}
```
Similarly, consider the case of iterator invalidation:
```rust,editable,compile_fail
fn main() {
let mut vec = vec![1, 2, 3, 4, 5];
for elem in &vec {
vec.push(elem * 2);
}
}
```
<details>
- In both of these cases, modifying the collection by pushing new elements into
it can potentially invalidate existing references to the collection's elements
if the collection has to reallocate.
</details>