Skip to content

Instantly share code, notes, and snippets.

@topecongiro
Created January 6, 2017 13:25
Show Gist options
  • Save topecongiro/f59e089e7fc6104e82896bd299b73300 to your computer and use it in GitHub Desktop.
Save topecongiro/f59e089e7fc6104e82896bd299b73300 to your computer and use it in GitHub Desktop.
A simple stack in Rust using Option and Box.
struct Node<T> {
val: T,
next: Option<Box<Node<T>>>,
}
pub struct Stack<T> {
top: Option<Box<Node<T>>>,
}
impl <T>Stack<T> {
pub fn new() -> Stack<T> {
Stack {
top: None,
}
}
pub fn push(&mut self, val: T) {
self.top = Some(Box::new(Node {
val: val,
next: self.top.take(),
}))
}
pub fn pop(&mut self) {
match self.top.take() {
None => return,
Some(mut node_box) => self.top = (*node_box).next.take(),
}
}
pub fn top(&self) -> &T {
match &self.top {
&None => panic!(),
&Some(ref node_box) => &(*node_box).val,
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment