File tree 1 file changed +26
-0
lines changed
1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change @@ -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,
You can’t perform that action at this time.
0 commit comments