diff --git a/src/doc/trpl/ownership.md b/src/doc/trpl/ownership.md index 9e3a3f12d1d2..055f6d82c6d7 100644 --- a/src/doc/trpl/ownership.md +++ b/src/doc/trpl/ownership.md @@ -207,7 +207,8 @@ We have to change our `main` a bit too: ```rust fn main() { - let mut x = 5; + let mut x = 5; // FIXME: remove this line? + // let mut x = Box::new(5); // This (box), used in previous exampl(s), still works add_one(&mut x); diff --git a/src/doc/trpl/pointers.md b/src/doc/trpl/pointers.md index 29986d7f2357..d42a33d95329 100644 --- a/src/doc/trpl/pointers.md +++ b/src/doc/trpl/pointers.md @@ -454,7 +454,8 @@ fn box_succ(x: Box) -> i32 { *x + 1 } fn rc_succ(x: Rc) -> i32 { *x + 1 } ``` -Note that the caller of your function will have to modify their calls slightly: +Note that the caller of your function will have to modify their calls slightly +(FIXME: actually they don't): ```{rust} use std::rc::Rc; @@ -466,8 +467,8 @@ let box_x = Box::new(5); let rc_x = Rc::new(5); succ(ref_x); -succ(&*box_x); -succ(&*rc_x); +succ(&*box_x); // FIXME: actually &box_x works fine +succ(&*rc_x); // FIXME: actually &rc_x works fine ``` The initial `*` dereferences the pointer, and then `&` takes a reference to @@ -560,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