1 // Rust-101, Part 04: Ownership, Borrowing, References
2 // ===================================================
5 void foo(std::vector<int> v) {
8 *first = 1337; // This is bad!
13 fn work_on_vector(v: Vec<i32>) { /* do something */ }
15 let v = vec![1,2,3,4];
17 /* println!("The first element is: {}", v[0]); */ /* BAD! */
20 // ## Borrowing a shared reference
22 fn vec_min(v: &Vec<i32>) -> Option<i32> {
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.
29 // In the loop, `e` now has type `&i32`, so we have to dereference it to obtain an `i32`.
30 min = Some(match min {
32 Some(n) => cmp::min(n, *e)
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];
44 println!("The first element is: {}", *first);
47 // ## Unique, mutable references
49 fn vec_inc(v: &mut Vec<i32>) {
50 for e in v.iter_mut() {
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]; */
60 /* println!("The first element is: {}", *first); */ /* BAD! */
64 // The ownership and borrowing system of Rust enforces the following three rules:
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
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.