diff options
| author | bors <bors@rust-lang.org> | 2014-11-27 04:32:12 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2014-11-27 04:32:12 +0000 |
| commit | f358ca45c8cf8a5ea8922b5c66403d6a4f4d52ad (patch) | |
| tree | 755e6d6f67ea238da49c5a697375b20b2513bc66 /src/doc/guide-pointers.md | |
| parent | fac5a07679cac21a580badc84b755b8df0f975cf (diff) | |
| parent | 5816d7f5305ce4401326568785d624e689064311 (diff) | |
| download | rust-f358ca45c8cf8a5ea8922b5c66403d6a4f4d52ad.tar.gz rust-f358ca45c8cf8a5ea8922b5c66403d6a4f4d52ad.zip | |
auto merge of #19342 : alexcrichton/rust/rollup, r=alexcrichton
Diffstat (limited to 'src/doc/guide-pointers.md')
| -rw-r--r-- | src/doc/guide-pointers.md | 31 |
1 files changed, 26 insertions, 5 deletions
diff --git a/src/doc/guide-pointers.md b/src/doc/guide-pointers.md index cf7ecd7e51f..8b6d00168e9 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>) -> int { *x + 1 } -fn rc_succ(x: std::rc::Rc<int>) -> int { *x + 1 } +fn rc_succ(x: Rc<int>) -> 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<T>` is Rust's 'boxed pointer' type. Boxes provide the simplest form of @@ -572,7 +593,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 +721,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 |
