]> git.proxmox.com Git - rustc.git/blobdiff - src/doc/book/references-and-borrowing.md
Imported Upstream version 1.10.0+dfsg1
[rustc.git] / src / doc / book / references-and-borrowing.md
index a08d53f958ba3eddcaa139646e7df4ef91f4f06a..a28f450c942af04cf36302c15483bb13df3a0a1c 100644 (file)
@@ -1,7 +1,7 @@
 % References and Borrowing
 
-This guide is two of three presenting Rust’s ownership system. This is one of
-Rust’s most unique and compelling features, with which Rust developers should
+This is the second of three sections presenting Rust’s ownership system. This is one of
+Rust’s most distinct and compelling features, with which Rust developers should
 become quite acquainted. Ownership is how Rust achieves its largest goal,
 memory safety. There are a few distinct concepts, each with its own
 chapter:
@@ -77,6 +77,32 @@ 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.
+    fn sum_vec(v: &Vec<i32>) -> 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<i32>, v2: &Vec<i32>) -> 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);
+}
+```
+
 Instead of taking `Vec<i32>`s as our arguments, we take a reference:
 `&Vec<i32>`. And instead of passing `v1` and `v2` directly, we pass `&v1` and
 `&v2`. We call the `&T` type a ‘reference’, and rather than owning the resource,