Help with Rc and RefCell

I've got a nested struct, where a child struct is saved in a member with "Rc<RefCell>".
When I want to access a method of Child in a main struct method with "(*child.borrow_mut()).child_method()" I get the following error message:

no method named child_method found for struct std::cell::RefCell in the current scope
method not found in std::cell::RefCell<Child>

I'm using the same syntax as I've found in examples found on the web. So I'm wondering what I'm doing wrong. Any help?

The repo of a full minimum example can be found here:

Please post the full error as reported by cargo build (in a code block).

It's because you have std::borrow::BorrowMut in scope and you're calling the wrong borrow_mut. Remove it from scope if you don't need it, or try

        let mut tabs = (*tabs).borrow_mut();

In more detail, the receivers considered when you call a .method() on your Rc<RefCell<T> are

  • Direct receiver
    • (1) Rc<RefCell>
    • (2) &Rc<RefCell>
    • (3) &mut Rc<RefCell>
  • By Deref coercion
    • (4) RefCell<T>
    • (5) &RefCell<T>
      • RefCell<T>::borrow_mut matches this one
    • (6) &mut RefCell<T>
      • <RefCell<T> as BorrowMut<RefCell<T>>>::borrow_mut also matches this one

When the BorrowMut trait is in scope, you get back a &mut Rc<RefCell<T>> and fail to call child_method() on it.

You can remove the BorrowMut trait to remove (3) (and (6)) from consideration, or you can explicitly dereference to start the candidate receivers at (4).

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.