Best way to hide borrow_mut

Hello,

For now, my struct looks like this:

pub struct A {
pub b:Rc<RefCell<B>>
}
pub struct B {
field:String
}

impl B {
pub fn update(&mut self,text:String){
self.field=text;
}
}

For now, I use it like the following to move it into a closure:

let a = A {
        b: Rc::new(RefCell::new(B {
            field: "hello".to_string(),
        })),
    };
    let clone = a.b.clone();
    clone.borrow_mut().update("updated".to_string());

What I would like is to remove borrow_mut and update the field from my update function like this:

let clone = a.b.clone();
clone.update("updated".to_string());

The question was asked to the wrong forum just for reference: Best way to hide borrow_mut - #3 by Alphapage - Rust Internals

Thank you in advance for your help.

Calling RefCell::borrow_mut is necessary to obtain a &mut B, which is necessary for calling update. The borrow_mut checks that there is no other active reference to B. In Rust, having a &mut reference gives exclusive access, meaning no other references to the value are allowed. With RefCell this is guaranteed using a runtime check as explained here:

An extension trait is another possibility.

2 Likes

You could add a &self method on A that calls borrow_mut() itself.

But generally you won't have many options for abstracting such things away in Rust. Rust uses the type system for memory management, so the implementation details of your memory management will affect the types.

Very clever way to hide borrow_mut, and it gives access to borrow_mut too if the user wants to use it :+1:
Thank you very much...