Last active
August 2, 2016 09:50
-
-
Save loggerhead/f21ad69603257648107c0ffb43a37699 to your computer and use it in GitHub Desktop.
A example of two object own each other.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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