Fix a RefCell already borrowed panic caused by a guard held across a call
add_half_price_copies must add a half-price copy of every item that costs more than 100. The program compiles, but at run time it panics with RefCell already borrowed. Find the borrow that is still alive when the panic happens and restructure the method.
Requirements:
addandadd_half_price_copieskeep their signatures and still take&self.mainstays as it is and prints[50, 200, 300, 100, 150].- No
unsafe, and notry_borrow_mutthat silently skips a write.
use std::cell::RefCell;
struct Cart {
items: RefCell<Vec<u32>>,
}
impl Cart {
fn add(&self, price: u32) {
self.items.borrow_mut().push(price);
}
fn add_half_price_copies(&self) {
for &price in self.items.borrow().iter() {
if price > 100 {
self.add(price / 2);
}
}
}
}
fn main() {
let cart = Cart {
items: RefCell::new(vec![50, 200, 300]),
};
cart.add_half_price_copies();
println!("{:?}", cart.items.borrow());
}Find and fix the bug.
The Ref from borrow() in the for header lives until the loop ends, and add calls borrow_mut() on the same RefCell inside it. Collect the half prices into a local Vec in one statement, so the guard drops, then call add.
- Assuming a
Refends at its last use, like a plain reference, instead of when the guard is dropped - Hiding the conflict with
try_borrow_mutand silently losing the writes - Overlooking that a temporary guard in a
forormatchheader lives for the whole loop ormatch
- Why does a
Reftaken in amatchscrutinee live until the end of the wholematch? - When is
try_borrow_muta correct fix rather than a way to hide the bug?
A temporary in a for header lives as long as the loop runs. So the Ref from self.items.borrow() holds a shared borrow through every iteration, and the very first self.add(...) runs into it in borrow_mut(). The compiler cannot see this: both calls take &self, and RefCell checks its rules at run time.
The fix is to finish reading before the first write. The needed prices are collected in one statement; at its end the guard is dropped, and add finds the RefCell free:
use std::cell::RefCell;
struct Cart {
items: RefCell<Vec<u32>>,
}
impl Cart {
fn add(&self, price: u32) {
self.items.borrow_mut().push(price);
}
fn add_half_price_copies(&self) {
let halves: Vec<u32> = self
.items
.borrow()
.iter()
.filter(|&&price| price > 100)
.map(|&price| price / 2)
.collect();
for price in halves {
self.add(price);
}
}
}
fn main() {
let cart = Cart {
items: RefCell::new(vec![50, 200, 300]),
};
cart.add_half_price_copies();
println!("{:?}", cart.items.borrow()); // [50, 200, 300, 100, 150]
}The behavior is now well defined as well: only the original items are scanned, and the added copies never join the scan. try_borrow_mut in add would remove the panic but silently lose both writes. The same bug appears with match self.items.borrow().first(): the guard lives until the end of the whole match, so the value is copied into a local variable first.