Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 12, 2018 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rust-play/3096c5b606b05e0fc06b8de85f422292 to your computer and use it in GitHub Desktop.
Save rust-play/3096c5b606b05e0fc06b8de85f422292 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::rc::{Rc,Weak};
use std::cell::RefCell;
#[derive(Debug)]
struct Node {
value: i32,
parent: RefCell<Weak<Node>>,
children: RefCell<Vec<Rc<Node>>>,
}
fn main() {
let leaf = Rc::new(Node {
value: 3,
children: RefCell::new(vec![]),
parent: RefCell::new(Weak::new()),
});
println!(
"leaf strong = {} weak = {}",
Rc::strong_count(&leaf),
Rc::weak_count(&leaf)
);
{
let branch = Rc::new(Node{
value:5,
children: RefCell::new(vec![Rc::clone(&leaf)]),
parent: RefCell::new(Weak::new()),
});
*leaf.parent.borrow_mut() = Rc::downgrade(&branch);
println!(
"branch strong = {} weak = {}",
Rc::strong_count(&branch),
Rc::weak_count(&branch),
);
println!(
"leaf strong = {} weak = {}",
Rc::strong_count(&leaf),
Rc::weak_count(&leaf)
);
}
println!("leaf parent = {:#?}", leaf.parent.borrow().upgrade());
println!(
"leaf strong = {} weak = {}",
Rc::strong_count(&leaf),
Rc::weak_count(&leaf),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment