Created
March 6, 2017 18:50
-
-
Save anonymous/8c67c7d3c5bf4d0f5495b30e2819a43d to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains hidden or 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
#[derive(Debug, PartialEq, Eq, Clone)] | |
struct Node<T: Clone> { | |
name: String, | |
value: T, | |
next: Option<Box<Node<T>>> | |
} | |
impl<T: PartialEq + Clone> Node<T> { | |
fn new(name: &str, value: T) -> Self { | |
Node { | |
name: name.to_owned(), | |
value: value, | |
next: None, | |
} | |
} | |
fn add(&mut self, node: Node<T>) { | |
match self.next { | |
None => self.next = Some(Box::new(node)), | |
Some(ref mut n) => n.add(node), | |
} | |
} | |
fn find(&mut self, val: T) -> Option<&Self> { | |
if self.value == val { | |
return Some(self) | |
} else { | |
match self.next { | |
Some(ref mut n) => n.find(val), | |
None => None, | |
} | |
} | |
} | |
} | |
fn main() { | |
let mut node = Node::new("head", 0); | |
node.add(Node::new("first", 1)); | |
node.add(Node::new("second", 2)); | |
node.add(Node::new("third", 3)); | |
node.add(Node::new("fourth", 4)); | |
println!("{:?}", node.find(1)); | |
println!("{:?}", node); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment