Skip to content

Commit 0fdce5c

Browse files
committed
Rollup merge of rust-lang#32991 - kindlychung:patch-2, r=steveklabnik
make the borrowing example more concrete
2 parents 80bff1e + 10abb66 commit 0fdce5c

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

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

+26
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,32 @@ let answer = foo(&v1, &v2);
7777
// we can use v1 and v2 here!
7878
```
7979

80+
A more concrete example:
81+
82+
```rust
83+
fn main() {
84+
// Don't worry if you don't understand how `fold` works, the point here is that an immutable reference is borrowed.
85+
fn sum_vec(v: &Vec<i32>) -> i32 {
86+
return v.iter().fold(0, |a, &b| a + b);
87+
}
88+
// Borrow two vectors and and sum them.
89+
// This kind of borrowing does not allow mutation to the borrowed.
90+
fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
91+
// do stuff with v1 and v2
92+
let s1 = sum_vec(v1);
93+
let s2 = sum_vec(v2);
94+
// return the answer
95+
s1 + s2
96+
}
97+
98+
let v1 = vec![1, 2, 3];
99+
let v2 = vec![4, 5, 6];
100+
101+
let answer = foo(&v1, &v2);
102+
println!("{}", answer);
103+
}
104+
```
105+
80106
Instead of taking `Vec<i32>`s as our arguments, we take a reference:
81107
`&Vec<i32>`. And instead of passing `v1` and `v2` directly, we pass `&v1` and
82108
`&v2`. We call the `&T` type a ‘reference’, and rather than owning the resource,

0 commit comments

Comments
 (0)