diff options
| author | Steve Klabnik <steve@steveklabnik.com> | 2016-04-28 09:51:43 -0400 |
|---|---|---|
| committer | Steve Klabnik <steve@steveklabnik.com> | 2016-04-28 09:51:43 -0400 |
| commit | 3c14116f64d3830f1f7d25600867c3e74fa6dbd2 (patch) | |
| tree | a84987bee7735c4eeee2cae3024d5a941043aec1 | |
| parent | 0f9ba992910b724bd198a196b5e408785911fdfc (diff) | |
| parent | 10abb666e48abdb747946db6de21317708e18cf5 (diff) | |
| download | rust-3c14116f64d3830f1f7d25600867c3e74fa6dbd2.tar.gz rust-3c14116f64d3830f1f7d25600867c3e74fa6dbd2.zip | |
Rollup merge of #32991 - kindlychung:patch-2, r=steveklabnik
make the borrowing example more concrete
| -rw-r--r-- | src/doc/book/references-and-borrowing.md | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/src/doc/book/references-and-borrowing.md b/src/doc/book/references-and-borrowing.md index a08d53f958b..67a8a82f2a3 100644 --- a/src/doc/book/references-and-borrowing.md +++ b/src/doc/book/references-and-borrowing.md @@ -77,6 +77,32 @@ let answer = foo(&v1, &v2); // we can use v1 and v2 here! ``` +A more concrete example: + +```rust +fn main() { + // Don't worry if you don't understand how `fold` works, the point here is that an immutable reference is borrowed. + fn sum_vec(v: &Vec<i32>) -> i32 { + return v.iter().fold(0, |a, &b| a + b); + } + // Borrow two vectors and and sum them. + // This kind of borrowing does not allow mutation to the borrowed. + fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 { + // do stuff with v1 and v2 + let s1 = sum_vec(v1); + let s2 = sum_vec(v2); + // return the answer + s1 + s2 + } + + let v1 = vec![1, 2, 3]; + let v2 = vec![4, 5, 6]; + + let answer = foo(&v1, &v2); + println!("{}", answer); +} +``` + Instead of taking `Vec<i32>`s as our arguments, we take a reference: `&Vec<i32>`. And instead of passing `v1` and `v2` directly, we pass `&v1` and `&v2`. We call the `&T` type a ‘reference’, and rather than owning the resource, |
