Question about RefCell::borrow_mut

I got confused of the example code blow of fn RefCell::borrow_mut in STD docs.

fn borrow_mut(&self) -> RefMut<'_, T>

use std::cell::RefCell;

let c = RefCell::new("hello".to_owned());

*c.borrow_mut() = "bonjour".to_owned();

assert_eq!(&*c.borrow(), "bonjour");

As RefCell::borrow_mut return a RefMut instance.
It seems the code is translated to the code blow. So the DerefMut is used to change the internal value of variable c.
Is there any explanation of thus behavior in Rust Reference or The Rust Book? :grinning:

#![allow(unused)]
fn main() {
    use std::cell::RefCell;

    let c = RefCell::new("hello".to_owned());
    {
        let mut d = c.borrow_mut();

        *d = "bonjour".to_owned();
    }

    //*c.borrow_mut() = "bonjour".to_owned();
    assert_eq!(&*c.borrow(), "bonjour");
}

The translation you did just makes a temporary explicit. See https://doc.rust-lang.org/stable/reference/expressions.html#temporaries. To fully understand the wording in that section, see also https://doc.rust-lang.org/stable/reference/expressions.html#place-expressions-and-value-expressions on what place expression contexts are.

1 Like

https://doc.rust-lang.org/stable/reference/expressions.html#temporaries
When using a value expression in most place expression contexts, a temporary unnamed memory location is created and initialized to that value.

After checked those two links. It`s clear now.
Thanks a lot.

1 Like

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.