Skip to content

Instantly share code, notes, and snippets.

@loggerhead
Last active August 2, 2016 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loggerhead/f21ad69603257648107c0ffb43a37699 to your computer and use it in GitHub Desktop.
Save loggerhead/f21ad69603257648107c0ffb43a37699 to your computer and use it in GitHub Desktop.
A example of two object own each other.
use std::rc::Rc;
use std::cell::RefCell;
struct Foo {
// Owns multiple mut trait objects
bars: Vec<Rc<RefCell<Bar>>>,
}
impl Foo {
fn new() -> Foo {
Foo { bars: vec![] }
}
fn add_bar(&mut self, bar: Rc<RefCell<Bar>>) {
self.bars.push(bar);
}
}
trait Bar {
fn add_foo(self, foo: Rc<RefCell<Foo>>);
}
struct Baz {
foo: Option<Rc<RefCell<Foo>>>,
}
impl Baz {
fn new() -> Baz {
Baz { foo: None }
}
}
impl Bar for Baz {
fn add_foo(self, foo: Rc<RefCell<Foo>>) {
let baz = Rc::new(RefCell::new(self));
foo.borrow_mut().add_bar(baz.clone());
baz.borrow_mut().foo = Some(foo);
}
}
fn main() {
let baz = Baz::new();
let foo = Foo::new();
baz.add_foo(Rc::new(RefCell::new(foo)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment