diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 004819b2d34..734208decf3 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -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) diff --git a/src/borrowing/examples.md b/src/borrowing/examples.md new file mode 100644 index 00000000000..f07f37d37fb --- /dev/null +++ b/src/borrowing/examples.md @@ -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); + } +} +``` + +
+ +- 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. + +