RefCell.borrow_mut get strange result


#1

Hi all, I just started to learn Rust, and am reading The Rust Programming Language . just read chap15, and I got confused about RefCell.borrow_mut method. below is my code, can anybody help to explain to me: why f1 output RefCell { value: "<borrowed>" } but not the same as f2 or f3. thanks for any help~

https://play.rust-lang.org/?gist=1f289e21f2fb2c89c01f832642b0ad08&version=stable


#2

Looks like you’ve discovered a neat—and undocumented—feature of RefCell!

When the RefCell is mutably borrowed, you cannot immutably borrow it to display its contents. But rather than panicking, the Debug impl puts "<borrowed>", which is nice for when you’re, you know, debugging. (it would perhaps be nicer if it didn’t put something that could be misinterpreted as a valid string value; but that’s besides the point)

If you want to print the actual contents, you need to limit the borrow’s scope.

let value = RefCell::new(5);
let v = Rc::new(value);

println!("v: {:?}", v); // v: RefCell { value: 5 }
{
    println!("v: {:?}", v); // v: RefCell { value: 5 }
    let q = &mut v.borrow_mut();
    println!("v: {:?}", v); // v: RefCell { value: "<borrowed>" }
    println!("v: {:?}", v); // v: RefCell { value: "<borrowed>" }
} // q's scope ends
println!("v: {:?}", v); // v: RefCell { value: 5 }

#3

It’s so great. Thanks so much~ :smile: