所有权和借款

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