1 // ***Remember to enable/add this part in `main.rs`!***
3 // Rust-101, Part 04: Ownership, Borrowing
4 // =======================================
7 void foo(std::vector<int> v) {
10 *first = 1337; // This is bad!
15 fn work_on_vector(v: Vec<i32>) { /* do something */ }
17 let v = vec![1,2,3,4];
19 /* println!("The first element is: {}", v[0]); */
22 // ## Shared borrowing
24 fn vec_min(v: &Vec<i32>) -> Option<i32> {
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_borrow_demo() {
40 let v = vec![5,4,3,2,1];
44 println!("The first element is: {}", *first);
47 // ## Mutable borrowing
49 fn vec_inc(v: &mut Vec<i32>) {
54 // Here's an example of calling `vec_inc`.
55 fn mutable_borrow_demo() {
56 let mut v = vec![5,4,3,2,1];
57 /* let first = &v[0]; */
60 /* println!("The first element is: {}", *first); */
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 borrow, then nobody else can have active access to the data
68 // * If there is an active shared borrow, then every other active access to the data is also a shared borrow
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.