Skip to content

Instantly share code, notes, and snippets.

@piboistudios
Forked from rust-play/playground.rs
Last active July 16, 2018 21:35
Show Gist options
  • Save piboistudios/67b350fe0d79c8158cf6cabf248f3f3b to your computer and use it in GitHub Desktop.
Save piboistudios/67b350fe0d79c8158cf6cabf248f3f3b to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
// 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