1 // Rust-101, Part 04: Ownership, Borrowing
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]); */
20 // ## Shared borrowing
22 fn vec_min(v: &Vec<i32>) -> Option<i32> {
27 // In the loop, `e` now has type `&i32`, so we have to dereference it to obtain an `i32`.
28 min = Some(match min {
30 Some(n) => cmp::min(n, *e)
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];
42 println!("The first element is: {}", *first);
45 // ## Mutable borrowing
47 fn vec_inc(v: &mut Vec<i32>) {
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]; */
58 /* println!("The first element is: {}", *first); */
62 // The ownership and borrowing system of Rust enforces the following three rules:
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
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.