Borrow Rules Enforce Exclusive Mutation
Immutable borrows may coexist, but a live borrow blocks mutation until its last use, which NLL then releases for an exclusive mutable borrow.
Code
fn main() {
let mut scores = vec![70, 82, 91];
// 多个不可变借用可以同时存在
let first = &scores[0];
let count = scores.len();
println!("first {first} of {count} scores");
// first 仍存活期间,可变借用会被编译器拒绝(取消注释无法编译):
// scores.push(99);
// 这是 first 的最后一次使用,之后借用结束(NLL)
println!("first after reads: {first}");
// 借用已结束,独占的可变借用现在可以获得
scores.push(99);
println!("after push: {scores:?}");
// 同一时刻只允许一个可变借用
let last = scores.last_mut().unwrap();
*last += 1;
println!("after bump: {scores:?}");
}How it works
Borrow Rules Enforce Exclusive Mutation keeps everything in the function main.
Applying it
The demo output is labeled (first, first after reads:, after push:), so every printed line maps back to its originating operation.
Statements that matter
let last = scores.last_mut().unwrap();
Interactive Tools for This Topic
FAQ
- What does Borrow Rules Enforce Exclusive Mutation print when run?
- Execute the whole file; each printed line is prefixed with a label like `first`, `first after reads:`, `after push:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.