Created
December 20, 2017 10:31
-
-
Save Ihindng/62c02c5b08b5f1cf8941edc63beb4839 to your computer and use it in GitHub Desktop.
point
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::rc::Weak; | |
use std::cell::RefCell; | |
struct Owner { | |
name: String, | |
gadgets: RefCell<Vec<Weak<Gadget>>>, | |
} | |
struct Gadget { | |
id: i32, | |
owner: Rc<Owner>, | |
} | |
fn main() { | |
let gadget_owner: Rc<Owner> = Rc::new(Owner { | |
name: "Gadget Man".to_string(), | |
gadgets: RefCell::new(Vec::new()), | |
}); | |
let gadget1 = Rc::new(Gadget { | |
id: 1, | |
owner: gadget_owner.clone(), | |
}); | |
let gadget2 = Rc::new(Gadget { | |
id: 2, | |
owner: gadget_owner.clone(), | |
}); | |
gadget_owner.gadgets.borrow_mut().push(Rc::downgrade(&gadget1)); | |
gadget_owner.gadgets.borrow_mut().push(Rc::downgrade(&gadget2)); | |
for gadget_opt in gadget_owner.gadgets.borrow().iter() { | |
let gadget = gadget_opt.upgrade().unwrap(); | |
println!("Gadget {} owned by {}", gadget.id, gadget.owner.name); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment