|
1 | 1 | % References and Borrowing
|
2 | 2 |
|
3 |
| -This guide is two of three presenting Rust’s ownership system. This is one of |
4 |
| -Rust’s most unique and compelling features, with which Rust developers should |
| 3 | +This is the second of three sections presenting Rust’s ownership system. This is one of |
| 4 | +Rust’s most distinct and compelling features, with which Rust developers should |
5 | 5 | become quite acquainted. Ownership is how Rust achieves its largest goal,
|
6 | 6 | memory safety. There are a few distinct concepts, each with its own
|
7 | 7 | chapter:
|
@@ -77,6 +77,32 @@ let answer = foo(&v1, &v2);
|
77 | 77 | // we can use v1 and v2 here!
|
78 | 78 | ```
|
79 | 79 |
|
| 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 | + |
80 | 106 | Instead of taking `Vec<i32>`s as our arguments, we take a reference:
|
81 | 107 | `&Vec<i32>`. And instead of passing `v1` and `v2` directly, we pass `&v1` and
|
82 | 108 | `&v2`. We call the `&T` type a ‘reference’, and rather than owning the resource,
|
|
0 commit comments