From 5429f9440548378c0beb56e890f4b6afe693ae2b Mon Sep 17 00:00:00 2001 From: kjpgit Date: Tue, 17 Mar 2015 11:48:57 -0500 Subject: [PATCH] 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 &*. --- src/doc/trpl/pointers.md | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/src/doc/trpl/pointers.md b/src/doc/trpl/pointers.md index 29986d7f23577..f05d2891e70ee 100644 --- a/src/doc/trpl/pointers.md +++ b/src/doc/trpl/pointers.md @@ -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} -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} -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