about summary refs log tree commit diff
diff options
context:
space:
mode:
authorkjpgit <kjpgit@users.noreply.github.com>2015-03-17 11:48:57 -0500
committerkjpgit <kjpgit@users.noreply.github.com>2015-03-17 11:52:14 -0500
commit5429f9440548378c0beb56e890f4b6afe693ae2b (patch)
tree26cdf2bdf526436fb5247bac4d380a02866fdd40
parent3d6f5100aff24aa97275dc92ade728caac605560 (diff)
downloadrust-5429f9440548378c0beb56e890f4b6afe693ae2b.tar.gz
rust-5429f9440548378c0beb56e890f4b6afe693ae2b.zip
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 &*.
-rw-r--r--src/doc/trpl/pointers.md28
1 files changed, 15 insertions, 13 deletions
diff --git a/src/doc/trpl/pointers.md b/src/doc/trpl/pointers.md
index 29986d7f235..f05d2891e70 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