Skip to content

Commit a3f5d8a

Browse files
committed
make the borrowing example more concrete
1 parent 74b3684 commit a3f5d8a

File tree

1 file changed

+20
-12
lines changed

1 file changed

+20
-12
lines changed

src/doc/book/references-and-borrowing.md

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -62,19 +62,27 @@ This is not idiomatic Rust, however, as it doesn’t take advantage of borrowing
6262
the first step:
6363

6464
```rust
65-
fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
66-
// do stuff with v1 and v2
67-
68-
// return the answer
69-
42
65+
fn main() {
66+
// Don't worry if you don't understand how `fold` works, the point here is that an immutable reference is borrowed.
67+
fn sum_vec(v: &Vec<i32>) -> i32 {
68+
return v.iter().fold(0, |a, &b| a + b);
69+
}
70+
// Borrow two vectors and and sum them.
71+
// This kind of borrowing does not allow mutation to the borrowed.
72+
fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
73+
// do stuff with v1 and v2
74+
let s1 = sum_vec(v1);
75+
let s2 = sum_vec(v2);
76+
// return the answer
77+
s1 + s2
78+
}
79+
80+
let v1 = vec![1, 2, 3];
81+
let v2 = vec![4, 5, 6];
82+
83+
let answer = foo(&v1, &v2);
84+
println!("{}", answer);
7085
}
71-
72-
let v1 = vec![1, 2, 3];
73-
let v2 = vec![1, 2, 3];
74-
75-
let answer = foo(&v1, &v2);
76-
77-
// we can use v1 and v2 here!
7886
```
7987

8088
Instead of taking `Vec<i32>`s as our arguments, we take a reference:

0 commit comments

Comments
 (0)