Split Borrows On Struct Fields
Two mutable borrows of different fields coexist because the borrow checker proves they are disjoint, while a whole-struct method would collide.
Code
#[derive(Debug)]
struct Account {
balance_cents: i64,
frozen: bool,
}
impl Account {
fn unfreeze(&mut self) {
self.frozen = false;
}
}
fn main() {
let mut acc = Account { balance_cents: -1, frozen: true };
// split borrows:同时可变借用同一 struct 的两个不同字段,
// 借用检查器能证明它们互不重叠
let balance = &mut acc.balance_cents;
let frozen = &mut acc.frozen;
if *balance < 0 {
*balance = 0;
}
*frozen = false;
println!("balance {} frozen {}", balance, frozen);
// 对比:整体 &mut self 的方法会与仍存活的字段借用冲突
let hold = &mut acc.frozen;
*hold = true;
// acc.unfreeze(); ← 放开这行无法编译:hold 还是活的独占借用
drop(hold); // 显式结束借用
acc.unfreeze(); // 现在才能整体可变借用
println!("{acc:?}");
}How it works
Split Borrows On Struct Fields reduces to the functions unfreeze and main.
Using it
The main signature reads fn unfreeze(&mut self)
The demo output is labeled (balance), so every printed line maps back to its originating operation.
The entry point wires unfreeze together — run it once and the whole demo flows.
Key statements
fn unfreeze(&mut self) {
self.frozen = false;
}
Interactive Tools for This Topic
FAQ
- What does Split Borrows On Struct Fields print when run?
- No setup needed: run the file and look for labeled lines like `balance` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.