quizzes
This commit is contained in:
45
practice/src/bin/m_node.rs
Normal file
45
practice/src/bin/m_node.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::{Rc, Weak};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Node {
|
||||
value: i32,
|
||||
parent: RefCell<Option<Weak<Node>>>, // <-- weak ref to parent
|
||||
children: RefCell<Vec<Rc<Node>>>,
|
||||
}
|
||||
|
||||
impl Node {
|
||||
fn new(value: i32) -> Rc<Self> {
|
||||
Rc::new(Self {
|
||||
value,
|
||||
parent: Default::default(),
|
||||
children: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn set_parent(&self, parent: Rc<Node>) {
|
||||
*self.parent.borrow_mut() = Some(Rc::downgrade(&parent)); // <-- create weak ref to parent
|
||||
}
|
||||
|
||||
fn add_child(self: &Rc<Self>, child: Rc<Node>) {
|
||||
child.set_parent(self.clone());
|
||||
self.children.borrow_mut().push(child);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Node {
|
||||
fn drop(&mut self) {
|
||||
println!(
|
||||
"Dropping node with value {} and {} children",
|
||||
self.value,
|
||||
self.children.borrow().len()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let tree = Node::new(1);
|
||||
tree.add_child(Node::new(3));
|
||||
tree.add_child(Node::new(5));
|
||||
println!("Finishing program now");
|
||||
}
|
||||
Reference in New Issue
Block a user