Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
use std::cell::RefCell;
fn main() {
let c = RefCell::new(1);
let mut a = c.borrow_mut();
*a += 1;
let mut b = c.borrow_mut();
*b += 1;
println!("{b}");
}It compiles and panics
- Expecting a compile error, as with two
&mut:borrow_muttakes&self, soRefCellchecks the rule only at run time, and breaking it is a panic. - Expecting
ato be released after its last use, like a reference: aRefMutguard keeps the borrow until it is dropped, here at the end ofmain.
- Which single line would you add so that the program prints
3? - How would calling
try_borrow_mutchange what happens on the second borrow?