-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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.
- Loading branch information
1 parent
59d63a6
commit 0c23d81
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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> |