summaryrefslogtreecommitdiff
path: root/tree
diff options
context:
space:
mode:
authorJordan Gong <jordan.gong@protonmail.com>2020-09-21 16:04:49 +0800
committerJordan Gong <jordan.gong@protonmail.com>2020-09-21 16:04:49 +0800
commita1a8008aab6a1c70ed2a5ecde9d2f3ad21b689bf (patch)
treea734d31fab43e55fb3a1149eb43bc24f532b2950 /tree
parentaddc4ab037ed8d0635841e5ca9db3a1768c42a11 (diff)
Use `Weak` to prevent reference cycles
Diffstat (limited to 'tree')
-rw-r--r--tree/.gitignore18
-rw-r--r--tree/Cargo.toml9
-rw-r--r--tree/src/main.rs55
3 files changed, 82 insertions, 0 deletions
diff --git a/tree/.gitignore b/tree/.gitignore
new file mode 100644
index 0000000..e629269
--- /dev/null
+++ b/tree/.gitignore
@@ -0,0 +1,18 @@
+
+# Created by https://www.toptal.com/developers/gitignore/api/rust
+# Edit at https://www.toptal.com/developers/gitignore?templates=rust
+
+### Rust ###
+# Generated by Cargo
+# will have compiled files and executables
+/target/
+
+# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
+# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
+Cargo.lock
+
+# These are backup files generated by rustfmt
+**/*.rs.bk
+
+# End of https://www.toptal.com/developers/gitignore/api/rust
+
diff --git a/tree/Cargo.toml b/tree/Cargo.toml
new file mode 100644
index 0000000..717cd24
--- /dev/null
+++ b/tree/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "tree"
+version = "0.1.0"
+authors = ["Jordan Gong <jordan.gong@protonmail.com>"]
+edition = "2018"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
diff --git a/tree/src/main.rs b/tree/src/main.rs
new file mode 100644
index 0000000..2c9f238
--- /dev/null
+++ b/tree/src/main.rs
@@ -0,0 +1,55 @@
+use std::cell::RefCell;
+use std::rc::{Rc, Weak};
+
+#[derive(Debug)]
+struct Node {
+ value: i32,
+ parent: RefCell<Weak<Node>>,
+ children: RefCell<Vec<Rc<Node>>>,
+}
+
+fn main() {
+ let leaf = Rc::new(Node {
+ value: 3,
+ parent: RefCell::new(Weak::new()),
+ children: RefCell::new(vec![]),
+ });
+
+ // println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
+
+ println!(
+ "leaf strong = {}, weak = {}",
+ Rc::strong_count(&leaf),
+ Rc::weak_count(&leaf),
+ );
+
+ {
+ let branch = Rc::new(Node {
+ value: 5,
+ parent: RefCell::new(Weak::new()),
+ children: RefCell::new(vec![Rc::clone(&leaf)]),
+ });
+
+ *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),
+ );
+}