Skip to content

Commit 5429f94

Browse files
committed
book: improve pointer box borrowing examples
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 &*.
1 parent 3d6f510 commit 5429f94

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
@@ -560,38 +560,40 @@ fn main() {
560560
In this case, Rust knows that `x` is being *borrowed* by the `add_one()`
561561
function, and since it's only reading the value, allows it.
562562

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

565565
```{rust}
566-
fn add_one(x: &i32) -> i32 {
567-
*x + 1
566+
fn add(x: &i32, y: &i32) -> i32 {
567+
*x + *y
568568
}
569569
570570
fn main() {
571571
let x = Box::new(5);
572572
573-
println!("{}", add_one(&*x));
574-
println!("{}", add_one(&*x));
575-
println!("{}", add_one(&*x));
573+
println!("{}", add(&x, &x));
574+
println!("{}", add(&x, &x));
576575
}
577576
```
578577

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

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

594-
Notice we changed the signature of `add_one()` to request a mutable reference.
596+
Notice the signature of `increment()` requests a mutable reference.
595597

596598
## Best practices
597599

0 commit comments

Comments
 (0)