Skip to content

book: improve pointer box borrowing examples #23447

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 20, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 15 additions & 13 deletions src/doc/trpl/pointers.md
Original file line number Diff line number Diff line change
@@ -560,38 +560,40 @@ fn main() {
In this case, Rust knows that `x` is being *borrowed* by the `add_one()`
function, and since it's only reading the value, allows it.

We can borrow `x` multiple times, as long as it's not simultaneous:
We can borrow `x` as read-only multiple times, even simultaneously:

```{rust}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rust still needed?

fn add_one(x: &i32) -> i32 {
*x + 1
fn add(x: &i32, y: &i32) -> i32 {
*x + *y
}

fn main() {
let x = Box::new(5);

println!("{}", add_one(&*x));
println!("{}", add_one(&*x));
println!("{}", add_one(&*x));
println!("{}", add(&x, &x));
println!("{}", add(&x, &x));
}
```

Or as long as it's not a mutable borrow. This will error:
We can mutably borrow `x` multiple times, but only if x itself is mutable, and
it may not be *simultaneously* borrowed:

```{rust,ignore}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This compiles now right? Does it still need ignore? Also, is rust still needed?

fn add_one(x: &mut i32) -> i32 {
*x + 1
fn increment(x: &mut i32) {
*x += 1;
}

fn main() {
let x = Box::new(5);
// If variable x is not "mut", this will not compile
let mut x = Box::new(5);

println!("{}", add_one(&*x)); // error: cannot borrow immutable dereference
// of `&`-pointer as mutable
increment(&mut x);
increment(&mut x);
println!("{}", x);
}
```

Notice we changed the signature of `add_one()` to request a mutable reference.
Notice the signature of `increment()` requests a mutable reference.

## Best practices