about summary refs log tree commit diff
diff options
context:
space:
mode:
authorManish Goregaokar <manishsmail@gmail.com>2015-03-20 05:30:49 +0530
committerManish Goregaokar <manishsmail@gmail.com>2015-03-20 12:43:12 +0530
commitdbe084b5bffae155b83f9229d04d83e7273bec4f (patch)
treed15613196de70e7db246c01d59fd51f4d6763ccb
parent1ceb26b48c0949fdc34feb1e190c4771db898af1 (diff)
parent5429f9440548378c0beb56e890f4b6afe693ae2b (diff)
downloadrust-dbe084b5bffae155b83f9229d04d83e7273bec4f.tar.gz
rust-dbe084b5bffae155b83f9229d04d83e7273bec4f.zip
Rollup merge of #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 &*.
-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 930a40c5050..39106aaf857 100644
--- a/src/doc/trpl/pointers.md
+++ b/src/doc/trpl/pointers.md
@@ -561,38 +561,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