part 09: explain how Rust prevents iterator invalidation
[rust-101.git] / workspace / src / part04.rs
1 // Rust-101, Part 04: Ownership, Borrowing
2 // =======================================
3
4 /*
5   void foo(std::vector<int> v) {
6       int *first = &v[0];
7       v.push_back(42);
8       *first = 1337; // This is bad!
9   }
10 */
11
12 // ## Ownership
13 fn work_on_vector(v: Vec<i32>) { /* do something */ }
14 fn ownership_demo() {
15     let v = vec![1,2,3,4];
16     work_on_vector(v);
17     /* println!("The first element is: {}", v[0]); */               /* BAD! */
18 }
19
20 // ## Shared borrowing
21
22 fn vec_min(v: &Vec<i32>) -> Option<i32> {
23     use std::cmp;
24
25     let mut min = None;
26     for e in v {
27         // In the loop, `e` now has type `&i32`, so we have to dereference it to obtain an `i32`.
28         min = Some(match min {
29             None => *e,
30             Some(n) => cmp::min(n, *e)
31         });
32     }
33     min
34 }
35
36 // Now that `vec_min` does not acquire ownership of the vector anymore, we can call it multiple times on the same vector and also do things like
37 fn shared_borrow_demo() {
38     let v = vec![5,4,3,2,1];
39     let first = &v[0];
40     vec_min(&v);
41     vec_min(&v);
42     println!("The first element is: {}", *first);
43 }
44
45 // ## Mutable borrowing
46
47 fn vec_inc(v: &mut Vec<i32>) {
48     for e in v {
49         *e += 1;
50     }
51 }
52 // Here's an example of calling `vec_inc`.
53 fn mutable_borrow_demo() {
54     let mut v = vec![5,4,3,2,1];
55     /* let first = &v[0]; */
56     vec_inc(&mut v);
57     vec_inc(&mut v);
58     /* println!("The first element is: {}", *first); */             /* BAD! */
59 }
60
61 // ## Summary
62 // The ownership and borrowing system of Rust enforces the following three rules:
63 // 
64 // * There is always exactly one owner of a piece of data
65 // * If there is an active mutable borrow, then nobody else can have active access to the data
66 // * If there is an active shared borrow, then every other active access to the data is also a shared borrow
67 // 
68 // As it turns out, combined with the abstraction facilities of Rust, this is a very powerful mechanism
69 // to tackle many problems beyond basic memory safety. You will see some examples for this soon.
70