Skip to content

Commit

Permalink
Merge pull request #1842 from rust-lang/add-nll-example
Browse files Browse the repository at this point in the history
Add an example that illustrates NLL
  • Loading branch information
carols10cents authored Mar 10, 2019
2 parents 506ce62 + 98e4db3 commit d7df985
Showing 1 changed file with 29 additions and 4 deletions.
33 changes: 29 additions & 4 deletions src/ch04-02-references-and-borrowing.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,10 +229,35 @@ from under them! However, multiple immutable references are okay because no one
who is just reading the data has the ability to affect anyone else’s reading of
the data.

Even though these errors may be frustrating at times, remember that it’s the
Rust compiler pointing out a potential bug early (at compile time rather than
at runtime) and showing you exactly where the problem is. Then you don’t have
to track down why your data isn’t what you thought it was.
Note that a reference's scope starts from where it is introduced and continues
through the last time that reference is used. For instance, this code will
compile because the last usage of the immutable references occurs before the
mutable reference is introduced:

<!-- This example is being ignored because there's a bug in rustdoc making the
edition2018 not work. The bug is currently fixed in nightly, so when we update
the book to >= 1.35, `ignore` can be removed from this example. -->

```rust,edition2018,ignore
let mut s = String::from("hello");
let r1 = &s; // no problem
let r2 = &s; // no problem
println!("{} and {}", r1, r2);
// r1 and r2 are no longer used after this point
let r3 = &mut s; // no problem
println!("{}", r3);
```

The scopes of the immutable references `r1` and `r2` end after the `println!`
where they are last used, which is before the mutable reference `r3` is
created. These scopes don't overlap, so this code is allowed.

Even though borrowing errors may be frustrating at times, remember that it’s
the Rust compiler pointing out a potential bug early (at compile time rather
than at runtime) and showing you exactly where the problem is. Then you don’t
have to track down why your data isn’t what you thought it was.

### Dangling References

Expand Down

0 comments on commit d7df985

Please sign in to comment.