Last active
April 16, 2026 19:23
-
-
Save wuhanstudio/cc56eb478dd7d9de27a42a7c7bb9d9d4 to your computer and use it in GitHub Desktop.
Rust RefCount and RefCell
This file contains hidden or 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; | |
| struct Parent { | |
| count: u32, | |
| } | |
| struct Child { | |
| parent: Rc<Parent>, | |
| } | |
| struct Family { | |
| parent: Rc<Parent>, | |
| child: Child, | |
| } | |
| impl Family { | |
| fn new() -> Self { | |
| let parent = Rc::new(Parent { count: 42}); | |
| let child = Child { parent: Rc::clone(&parent) }; | |
| Family { parent: parent, child: child} | |
| } | |
| } | |
| fn main () { | |
| let family = Family::new(); | |
| println!("Parent is {}", family.parent.count); | |
| println!("Child is {}", family.child.parent.count); | |
| } |
This file contains hidden or 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; | |
| #[derive(Debug)] | |
| struct Parent { | |
| count: RefCell<u32>, | |
| } | |
| #[derive(Debug)] | |
| struct Child { | |
| parent: Rc<Parent>, | |
| } | |
| #[derive(Debug)] | |
| struct Family { | |
| parent: Rc<Parent>, | |
| child: Child, | |
| } | |
| impl Family { | |
| fn new() -> Self { | |
| let parent = Rc::new(Parent { count: RefCell::new(42) }); | |
| let child = Child { parent: Rc::clone(&parent) }; | |
| Family { parent: parent, child: child} | |
| } | |
| } | |
| fn main () { | |
| let family = Family::new(); | |
| println!("Parent is {}", family.parent.count.borrow()); | |
| println!("Child is {}", family.child.parent.count.borrow()); | |
| { | |
| let mut count = family.parent.count.borrow_mut(); | |
| *count += 1; | |
| println!("Count is {}", *count); | |
| } | |
| println!("Parent is {}", family.parent.count.borrow()); | |
| println!("Child is {}", family.child.parent.count.borrow()); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment