借用检查

Rust’s borrow checker puts constraints on the ways you can borrow values. For a given value, at any time:

  • You can have one or more shared references to the value, or
  • You can have exactly one exclusive reference to the value.
fn main() {
    let mut a: i32 = 10;
    let b: &i32 = &a;

    {
        let c: &mut i32 = &mut a;
        *c = 20;
    }

    println!("a: {a}");
    println!("b: {b}");
}
This slide should take about 10 minutes.
  • 请注意,要求是相冲突的引用不能 同时存在。而引用的解引用位置无关紧要。
  • 上述代码无法编译,因为 a 同时作为可变值(通过 c)和不可变值(通过 b)被借用。
  • bprintln! 语句移到引入 c 的作用域之前,这段代码就可以编译。
  • 这样更改后,编译器会发现 b 只在通过 ca 进行新可变借用之前使用过。这是借用检查器的一个功能,名为“非词法作用域生命周期”。
  • The exclusive reference constraint is quite strong. Rust uses it to ensure that data races do not occur. Rust also relies on this constraint to optimize code. For example, a value behind a shared reference can be safely cached in a register for the lifetime of that reference.
  • 借用检查器专用于处理许多常见模式,例如同时对结构体中的不同字段进行独占引用。但在某些情况下,它并不能完全 “领会”您的意图,这往往会导致 “与借用检查器进行一番斗争”。