About borrow_mut in refcell

x is defined as

 let x = RefCell::new(vec![1, 2, 3, 4]);

What's the differences between the following? why the first no panics while they actually execute the same code?

x.borrow_mut().push(5);
println!("refcell: {:?}", x.borrow());

and this panics:

let mut m = x.borrow_mut();
m.push(5);
println!("refcell: {:?}", x.borrow());

m is still alive while the println runs, resulting in a double borrow

try:

{
let mut m = x.borrow_mut();
m.push(5);
}
println!("refcell: {:?}", x.borrow());

this ensures m drops before the println runs

1 Like

In your first example, the mutable reference you obtain to the cell is dropped after push. In your second example, it is dropped at the end of the scope where you declare your let binding. If you try to get a second borrow while the first one is still around, you get a panic.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.