所有權和借款

Rust 中的所有值都只有一個所有者。所有者負責在超出範圍時刪除該值,並且是唯一可以移動該值的所有權的人。值的所有者可以通過讓其他程式碼段借用該值來放棄對它的引用。在任何給定時間,可能存在任意數量的值的不可變引用: **

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;

或者單個可變引用(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

如果某個值存在未完成的引用(可變或不可變),則無法移動該值(即,將其所有權放棄)。我們必須確保首先刪除所有引用以允許移動值:

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