Created
July 16, 2018 21:35
-
-
Save rust-play/6292795b5e25b1bfe3616f0710e8b991 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains 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
// Author: Gabriel Hayes | |
use std::cell::RefCell; | |
use std::rc::{Rc, Weak}; | |
#[derive(Debug)] | |
struct Node { | |
val: i64, | |
children: Vec<Rc<RefCell<Node>>>, | |
parent: RefCell<Weak<Node>> | |
} | |
impl Node { | |
fn new() -> Node { | |
Node { | |
val: 0, | |
children: Vec::new(), | |
parent: RefCell::new(Weak::new()) | |
} | |
} | |
fn init(val:i64) -> Node { | |
let mut node = Node::new(); | |
node.val = val; | |
node | |
} | |
fn add_child(&mut self, child: RefCell<Node>) { | |
self.children.push(Rc::new(child)); | |
} | |
fn get_parent(&self) -> Rc<Node> { | |
self.parent.borrow().upgrade().unwrap() | |
} | |
fn get_children(&self) -> Vec<Rc<RefCell<Node>>> { | |
let mut ret = vec![]; | |
for childref in self.children.iter() { | |
ret.push(childref.clone()); | |
} | |
ret | |
} | |
} | |
fn main() { | |
let mut root = Node::init(10); | |
let mut some_branch = Node::init(21); | |
let mut another_branch = Node::init(5); | |
root.add_child(RefCell::new(some_branch)); | |
root.add_child(RefCell::new(another_branch)); | |
println!("root = {:#?}", root); | |
println!("root.get_children() = {:#?}", root.get_children()); | |
// println!("some_branch = {:#?}", some_branch); | |
// println!("another_branch = {:#?}", another_branch); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment