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ż
ajest pożyczone jako mutowalne (przezc) i jako niemutowalne (przezb) w tym samym czasie. - Przenieś instrukcję
println!dlabprzed zakres, który wprowadzac, żeby kod się kompilował. - Po zmianie, kompilator uświadomi sobie, że
bjest tylko używane przed mutowalnym pożyczeniemaprzezc. 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.”