Skip to content

Commit dbe084b

Browse files
committed
Rollup merge of rust-lang#23447 - kjpgit:kjp/pointerexample, r=steveklabnik
These two borrowing examples were confusing/misleading. This changes it to more clearly show how you _can_ borrow a box, and also uses & instead of &*.
2 parents 1ceb26b + 5429f94 commit dbe084b

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

src/doc/trpl/pointers.md

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -561,38 +561,40 @@ fn main() {
561561
In this case, Rust knows that `x` is being *borrowed* by the `add_one()`
562562
function, and since it's only reading the value, allows it.
563563

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

566566
```{rust}
567-
fn add_one(x: &i32) -> i32 {
568-
*x + 1
567+
fn add(x: &i32, y: &i32) -> i32 {
568+
*x + *y
569569
}
570570
571571
fn main() {
572572
let x = Box::new(5);
573573
574-
println!("{}", add_one(&*x));
575-
println!("{}", add_one(&*x));
576-
println!("{}", add_one(&*x));
574+
println!("{}", add(&x, &x));
575+
println!("{}", add(&x, &x));
577576
}
578577
```
579578

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

582582
```{rust,ignore}
583-
fn add_one(x: &mut i32) -> i32 {
584-
*x + 1
583+
fn increment(x: &mut i32) {
584+
*x += 1;
585585
}
586586
587587
fn main() {
588-
let x = Box::new(5);
588+
// If variable x is not "mut", this will not compile
589+
let mut x = Box::new(5);
589590
590-
println!("{}", add_one(&*x)); // error: cannot borrow immutable dereference
591-
// of `&`-pointer as mutable
591+
increment(&mut x);
592+
increment(&mut x);
593+
println!("{}", x);
592594
}
593595
```
594596

595-
Notice we changed the signature of `add_one()` to request a mutable reference.
597+
Notice the signature of `increment()` requests a mutable reference.
596598

597599
## Best practices
598600

0 commit comments

Comments
 (0)