Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: How to make a mutable reference from Child to Parent?
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
🏷️ rust_feed