How to make a mutable reference from Child to Parent?

⚓ rust    📅 2025-06-18    👤 surdeus    👁️ 3      

surdeus

Hello everyone
How to make a mutable reference from Child to Parent?

Smth like a Rust Playground

use std::cell::RefCell;

struct Child {
    parent: RefCell<Parent>,
}

impl Child {
    pub fn new (parent: RefCell<Parent>) -> Self {
        Self {
            parent: parent,
        }
    }
    pub fn print(& mut self) {
        println!("{}", self.parent.borrow_mut().value);
    }
}

struct Parent {
    pub value: i32,
}

impl Parent {
    pub fn new() -> Self {
        Self {
            value: 0,
        }
    }
    pub fn create_child(&self) -> Child {
        Child::new(RefCell::new(self))
    }
}

fn main() {
    let mut p = Parent::new();
    let mut c = p.create_child();
    c.print();
}

but this snipped is failing with

29  |         Child::new(RefCell::new(self))
    |                    ------------ ^^^^ expected `Parent`, found `&Parent`
    |                    |
    |                    arguments to this function are incorrect

Parent can create instance of Childs, but Parent also has some shared mutable field, that accessible for all childs.

Any ideas?

4 posts - 3 participants

Read full topic

🏷️ rust_feed