I am trying to write a container structure in Rust, where its elements also store a reference to the containing container so that they can call methods on it. As far as I can understand, I need to do this via Rc<RefCell<T>> . Is it correct?
So far, I have something like the following:
struct Container { elems: ~[~Element] } impl Container { pub fn poke(&mut self) { println!("Got poked."); } } struct Element { datum: int, container: Weak<RefCell<Container>> } impl Element { pub fn poke_container(&mut self) { let c1 = self.container.upgrade().unwrap();
I feel that something is missing here. Is access to the contents of Rc<RefCell<T>> really complicated (in poke_container )? Or am I getting the problem wrong?
Finally, assuming the approach is correct, how would I write the add method for Container so that it can fill the Container field in Element (assuming I changed the field like Option<Rc<RefCell<T>>> ? I can't create another Rc from &mut self , as far as I know.
Kolja source share