fn main() { let mut list = List::new(); list.push(1); println!("push(1) : {:?}", list); list.push(2); println!("push(2) : {:?}", list); println!("pop() -> {} : {:?}", list.pop().unwrap(), list); println!("pop() -> {} : {:?}", list.pop().unwrap(), list); } #[derive(Debug)] pub struct List { head: Link, } type Link = Option>>; #[derive(Debug)] struct Node { elem: T, next: Link, } impl List { pub fn new() -> Self { Self { head: None } } pub fn push(&mut self, elem: T) { let new_node = Node { elem: elem, next: self.head.take(), }; self.head = Some(Box::new(new_node)); } pub fn pop(&mut self) -> Option { self.head.take().map(|node| { self.head = node.next; node.elem }) } } #[cfg(test)] mod tests { use super::*; #[test] fn test() { let mut list = List::new(); assert_eq!(None, list.pop()); list.push(42); assert_eq!(Some(42), list.pop()); assert_eq!(None, list.pop()); } }