Learn Rust With Entirely Too Many Linked Lists
08

Final Code

Eight short sections, one working stack. The chapter is "bad" because we used i32 instead of a generic, reinvented Option, and skipped peek and iter. We'll fix all of that next chapter.

  1. The whole module — keep it open in another tab while reading the next chapter; we'll refactor against this baseline.
    use std::mem;
    
    pub struct List {
        head: Link,
    }
    
    enum Link {
        Empty,
        More(Box<Node>),
    }
    
    struct Node {
        elem: i32,
        next: Link,
    }
    
    impl List {
        pub fn new() -> Self {
            List { head: Link::Empty }
        }
    
        pub fn push(&mut self, elem: i32) {
            let new_node = Box::new(Node {
                elem,
                next: mem::replace(&mut self.head, Link::Empty),
            });
            self.head = Link::More(new_node);
        }
    
        pub fn pop(&mut self) -> Option<i32> {
            match mem::replace(&mut self.head, Link::Empty) {
                Link::Empty => None,
                Link::More(node) => {
                    self.head = node.next;
                    Some(node.elem)
                }
            }
        }
    }
    
    impl Drop for List {
        fn drop(&mut self) {
            let mut cur = mem::replace(&mut self.head, Link::Empty);
            while let Link::More(mut node) = cur {
                cur = mem::replace(&mut node.next, Link::Empty);
            }
        }
    }