From 71b8b04f48a3c596a50d78405eb5b0eea80ad8e6 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Tue, 25 Nov 2014 10:57:17 -0500 Subject: Make note about cross-borrowing. Fixes #19302. --- src/doc/guide-pointers.md | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) (limited to 'src/doc/guide-pointers.md') diff --git a/src/doc/guide-pointers.md b/src/doc/guide-pointers.md index cf7ecd7e51f..64b440259cf 100644 --- a/src/doc/guide-pointers.md +++ b/src/doc/guide-pointers.md @@ -445,11 +445,32 @@ fn succ(x: &int) -> int { *x + 1 } to ```{rust} +use std::rc::Rc; + fn box_succ(x: Box) -> int { *x + 1 } -fn rc_succ(x: std::rc::Rc) -> int { *x + 1 } +fn rc_succ(x: Rc) -> int { *x + 1 } +``` + +Note that the caller of your function will have to modify their calls slightly: + +```{rust} +use std::rc::Rc; + +fn succ(x: &int) -> int { *x + 1 } + +let ref_x = &5i; +let box_x = box 5i; +let rc_x = Rc::new(5i); + +succ(ref_x); +succ(&*box_x); +succ(&*rc_x); ``` +The initial `*` dereferences the pointer, and then `&` takes a reference to +those contents. + # Boxes `Box` is Rust's 'boxed pointer' type. Boxes provide the simplest form of -- cgit 1.4.1-3-g733a5 From 6cb03baffa329f785bdef4079456dc85ec3b0bbc Mon Sep 17 00:00:00 2001 From: Ulysse Carion Date: Tue, 25 Nov 2014 16:32:53 -0800 Subject: Fix formatting of the pointers guide. --- src/doc/guide-pointers.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src/doc/guide-pointers.md') diff --git a/src/doc/guide-pointers.md b/src/doc/guide-pointers.md index cf7ecd7e51f..08d7c2a4158 100644 --- a/src/doc/guide-pointers.md +++ b/src/doc/guide-pointers.md @@ -572,7 +572,7 @@ fn add_one(x: &mut int) -> int { fn main() { let x = box 5i; - println!("{}", add_one(&*x)); // error: cannot borrow immutable dereference + println!("{}", add_one(&*x)); // error: cannot borrow immutable dereference // of `&`-pointer as mutable } ``` @@ -700,9 +700,9 @@ This gives you flexibility without sacrificing performance. You may think that this gives us terrible performance: return a value and then immediately box it up ?! Isn't that the worst of both worlds? Rust is smarter -than that. There is no copy in this code. main allocates enough room for the -`box , passes a pointer to that memory into foo as x, and then foo writes the -value straight into that pointer. This writes the return value directly into +than that. There is no copy in this code. `main` allocates enough room for the +`box`, passes a pointer to that memory into `foo` as `x`, and then `foo` writes +the value straight into that pointer. This writes the return value directly into the allocated box. This is important enough that it bears repeating: pointers are not for -- cgit 1.4.1-3-g733a5