From a3f5d8aea1e43a1c5b0814dac407e6ddfab07417 Mon Sep 17 00:00:00 2001 From: Kaiyin Zhong Date: Fri, 15 Apr 2016 18:12:52 +0200 Subject: [PATCH 1/2] make the borrowing example more concrete --- src/doc/book/references-and-borrowing.md | 32 +++++++++++++++--------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/src/doc/book/references-and-borrowing.md b/src/doc/book/references-and-borrowing.md index a08d53f958ba3..3a1f3f004be62 100644 --- a/src/doc/book/references-and-borrowing.md +++ b/src/doc/book/references-and-borrowing.md @@ -62,19 +62,27 @@ This is not idiomatic Rust, however, as it doesn’t take advantage of borrowing the first step: ```rust -fn foo(v1: &Vec, v2: &Vec) -> i32 { - // do stuff with v1 and v2 - - // return the answer - 42 +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 { + 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, v2: &Vec) -> 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); } - -let v1 = vec![1, 2, 3]; -let v2 = vec![1, 2, 3]; - -let answer = foo(&v1, &v2); - -// we can use v1 and v2 here! ``` Instead of taking `Vec`s as our arguments, we take a reference: From 10abb666e48abdb747946db6de21317708e18cf5 Mon Sep 17 00:00:00 2001 From: Kaiyin Zhong Date: Tue, 26 Apr 2016 17:40:59 +0200 Subject: [PATCH 2/2] Update references-and-borrowing.md add as 2nd example. --- src/doc/book/references-and-borrowing.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/doc/book/references-and-borrowing.md b/src/doc/book/references-and-borrowing.md index 3a1f3f004be62..67a8a82f2a33b 100644 --- a/src/doc/book/references-and-borrowing.md +++ b/src/doc/book/references-and-borrowing.md @@ -61,6 +61,24 @@ let (v1, v2, answer) = foo(v1, v2); This is not idiomatic Rust, however, as it doesn’t take advantage of borrowing. Here’s the first step: +```rust +fn foo(v1: &Vec, v2: &Vec) -> i32 { + // do stuff with v1 and v2 + + // return the answer + 42 +} + +let v1 = vec![1, 2, 3]; +let v2 = vec![1, 2, 3]; + +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.