Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Pożyczanie

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.
  • Note that the requirement is that conflicting references not exist at the same point. It does not matter where the reference is dereferenced.
  • Powyższy kod się nie kompiluje ponieważ a jest pożyczone jako mutowalne (przez c) i jako niemutowalne (przez b) w tym samym czasie.
  • Przenieś instrukcję println! dla b przed zakres, który wprowadza c, żeby kod się kompilował.
  • Po zmianie, kompilator uświadomi sobie, że b jest tylko używane przed mutowalnym pożyczeniem a przez c. Ta funkcja nadzorcy pożyczania nazywa się “nieleksykalne czasy życia” (ang. non-lexical lifetimes).
  • 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.
  • The borrow checker is designed to accommodate many common patterns, such as taking exclusive references to different fields in a struct at the same time. But, there are some situations where it doesn’t quite “get it” and this often results in “fighting with the borrow checker.”