Rust Ownership Ownership and borrowing


All values in Rust have exactly one owner. The owner is responsible for dropping that value when it goes out of scope, and is the only one who may move the ownership of the value. The owner of a value may give away references to it by letting other pieces of code borrow that value. At any given time, there may be any number of immutable references to a value:

let owned = String::from("hello");
// since we own the value, we may let other variables borrow it
let immutable_borrow1 = &owned;
// as all current borrows are immutable, we can allow many of them
let immutable_borrow2 = &owned;
// in fact, if we have an immutable reference, we are also free to
// duplicate that reference, since we maintain the invariant that
// there are only immutable references
let immutable_borrow3 = &*immutable_borrow2;

or a single mutable reference to it (ERROR denotes a compile-time error):

// for us to borrow a value mutably, it must be mutable
let mut owned = String::from("hello");
// we can borrow owned mutably
let mutable_borrow = &mut owned;
// but note that we cannot borrow owned *again*
let mutable_borrow2 = &mut owned; // ERROR, already borrowed
// nor can we cannot borrow owned immutably
// since a mutable borrow is exclusive.
let immutable_borrow = &owned; // ERROR, already borrowed

If there are outstanding references (either mutable or immutable) to a value, that value cannot be moved (i.e., its ownership given away). We would have to make sure all references were dropped first to be allowed to move a value:

let foo = owned; // ERROR, outstanding references to owned
let owned = String::from("hello");
    let borrow = &owned;
    // ...
} // the scope ends the borrow
let foo = owned; // OK, owned and not borrowed