Skip to content

Instantly share code, notes, and snippets.

@sstelfox
Created July 28, 2019 21:31
Show Gist options
  • Save sstelfox/feabd0b1515e3ec490bf11732da85a47 to your computer and use it in GitHub Desktop.
Save sstelfox/feabd0b1515e3ec490bf11732da85a47 to your computer and use it in GitHub Desktop.
Playing around and attempting to figure out somethings around lifetimes, and recursive objects using traits.
trait Node: std::fmt::Debug {
fn value(&self) -> usize;
fn visit(&self) -> Result<usize, &str>;
}
#[derive(Debug)]
struct FixedNode;
impl Node for FixedNode {
fn value(&self) -> usize { 100 }
fn visit(&self) -> Result<usize, &str> { Ok(self.value()) }
}
#[derive(Debug)]
struct ParentNode {
child: Box<dyn Node>,
}
impl Node for ParentNode {
fn value(&self) -> usize {
self.child.value()
}
fn visit(&self) -> Result<usize, &str> {
self.child.visit()
}
}
#[derive(Debug)]
struct TreeNode<'a> {
left: Box<dyn Node + 'a>,
right: Box<dyn Node + 'a>,
}
impl<'a> TreeNode<'a> {
fn new(left: Box<impl Node + 'a>, right: Box<impl Node + 'a>) -> Self {
TreeNode {
left: left,
right: right,
}
}
}
impl Node for TreeNode<'_> {
fn value(&self) -> usize {
match self.visit() {
Ok(usize) => usize,
Err(_) => 0,
}
}
fn visit(&self) -> Result<usize, &str> {
let left_res = self.left.visit()?;
let right_res = self.right.visit()?;
Ok(left_res + right_res)
}
}
fn play_with_node(node: impl Node) {
println!("{:?}", node);
println!("{}", node.value());
println!("{:?}", node.visit());
}
fn main() {
let f1_node = FixedNode { };
let f2_node = FixedNode { };
let p_node = ParentNode { child: Box::new(f1_node) };
let t_node = TreeNode::new(Box::new(f2_node), Box::new(p_node));
play_with_node(t_node);
// Output:
// TreeNode { left: FixedNode, right: ParentNode { child: FixedNode } }
// 200
// Ok(200)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment