Skip to content

Instantly share code, notes, and snippets.

@wuhanstudio
Last active April 16, 2026 19:23
Show Gist options
  • Select an option

  • Save wuhanstudio/cc56eb478dd7d9de27a42a7c7bb9d9d4 to your computer and use it in GitHub Desktop.

Select an option

Save wuhanstudio/cc56eb478dd7d9de27a42a7c7bb9d9d4 to your computer and use it in GitHub Desktop.
Rust RefCount and RefCell
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);
}
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