re-do deepaksirone's fix on the actual source file
[rust-101.git] / workspace / src / part04.rs
1 // Rust-101, Part 04: Ownership, Borrowing, References
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 // ## Borrowing a shared reference
21
22 fn vec_min(v: &Vec<i32>) -> Option<i32> {
23     use std::cmp;
24
25     let mut min = None;
26     // This time, we explicitly request an iterator for the vector `v`. The method `iter` just borrows the vector
27     // it works on, and provides shared references to the elements.
28     for e in v.iter() {
29         // In the loop, `e` now has type `&i32`, so we have to dereference it to obtain an `i32`.
30         min = Some(match min {
31             None => *e,
32             Some(n) => cmp::min(n, *e)
33         });
34     }
35     min
36 }
37
38 // 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
39 fn shared_ref_demo() {
40     let v = vec![5,4,3,2,1];
41     let first = &v[0];
42     vec_min(&v);
43     vec_min(&v);
44     println!("The first element is: {}", *first);
45 }
46
47 // ## Unique, mutable references
48
49 fn vec_inc(v: &mut Vec<i32>) {
50     for e in v.iter_mut() {
51         *e += 1;
52     }
53 }
54 // Here's an example of calling `vec_inc`.
55 fn mutable_ref_demo() {
56     let mut v = vec![5,4,3,2,1];
57     /* let first = &v[0]; */
58     vec_inc(&mut v);
59     vec_inc(&mut v);
60     /* println!("The first element is: {}", *first); */             /* BAD! */
61 }
62
63 // ## Summary
64 // The ownership and borrowing system of Rust enforces the following three rules:
65 // 
66 // * There is always exactly one owner of a piece of data
67 // * If there is an active mutable reference, then nobody else can have active access to the data
68 // * If there is an active shared reference, then every other active access to the data is also a shared reference
69 // 
70 // As it turns out, combined with the abstraction facilities of Rust, this is a very powerful mechanism
71 // to tackle many problems beyond basic memory safety. You will see some examples for this soon.
72