Start learning free

LESSON 65 OF 69 · PROJECTS: OBJECT-ORIENTED

Stack Impl in Rust: Build a MyStack Struct on a Vec

Practice Read the full explanation

A stack is a pile where you only touch the top: the last value you put in is the first one you take out (LIFO, last in, first out), like a pile of plates. Build a class MyStack that stores whole numbers in a data: Vec<i32> field in struct MyStack and offers four operations.

The methods:

  • fn push(&mut self, value: i32)
  • fn pop(&mut self) -> i32
  • fn peek(&self) -> i32
  • fn size(&self) -> usize

Rules:

  • push puts the value on top of the stack. It returns nothing.
  • pop removes the top value (the one pushed last) and returns it.
  • peek returns the top value but leaves it on the stack, so the size does not change.
  • size returns how many values are on the stack. A new stack has size 0, and after popping everything the size is 0 again.
  • The stack keeps working after it becomes empty: you can push again.
  • Calling pop or peek on an empty stack is not part of this exercise and the tests never do it. (In Rust, unwrap() on an empty stack panics.)

You start with: The starter has an empty mainFunction: type this code inside it after the class.

let mut s = MyStack::new();
s.push(10);
s.push(20);
s.push(30);
println!("Top: {}", s.peek());
println!("Size: {}", s.size());
println!("Pop: {}", s.pop());
println!("Size: {}", s.size());
println!("Pop: {}", s.pop());
println!("Pop: {}", s.pop());
println!("Empty size: {}", s.size());
s.push(7);
println!("Top: {}", s.peek());
println!("Size: {}", s.size());

Expected output:

Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1

Reading the output: after pushing 10, 20 and 30 the top is 30 and the size 3. Popping gives 30, leaving size 2. Two more pops give 20 and then 10 (last in, first out), the stack is empty (size 0), and after pushing 7 the top is 7 and the size 1.


The top of the stack is the end of the list: adding and removing at the end is fast, and the last value pushed is always the last element.

A Vec has push, pop() (returns an Option, so call .unwrap()) and last() (an Option<&i32>, so write *self.data.last().unwrap()). Add a fn new() -> MyStack that returns MyStack { data: Vec::new() }. Methods that change the stack take &mut self.

struct MyStack {
    data: Vec<i32>,
}
impl MyStack {
    fn new() -> MyStack {
        MyStack { data: Vec::new() }
    }
    fn push(&mut self, value: i32) {
        self.data.push(value);
    }
    fn pop(&mut self) -> i32 {
        self.data.pop().unwrap()
    }
    fn peek(&self) -> i32 {
        *self.data.last().unwrap()
    }
    fn size(&self) -> usize {
        self.data.len()
    }
}

STEP 1 OF 24
    Ctrl + Enter to check

    RUST · PROJECTS: OBJECT-ORIENTED

    Stack Impl in Rust, explained

    Problem overview

    A stack is a pile where you only touch the top. The last value you put in is the first one you take out (LIFO, last in, first out), like a pile of plates. You build MyStack, a struct that stores whole numbers in a field data: Vec<i32> and offers four operations:

    • push(&mut self, value: i32) puts a value on top.
    • pop(&mut self) -> i32 removes the top value and returns it.
    • peek(&self) -> i32 returns the top value and leaves it in place.
    • size(&self) -> usize returns how many values are stored.

    The tests never call pop or peek on an empty stack. After the struct, you type a driver into mainFunction. It pushes 10, 20 and 30, peeks, pops all three, pushes 7 and peeks again. The expected output is:

    Top: 30
    Size: 3
    Pop: 30
    Size: 2
    Pop: 20
    Pop: 10
    Empty size: 0
    Top: 7
    Size: 1
    

    Approach: the end of the vector is the top

    A Vec already does what a stack needs at one end: adding at the end and removing from the end. So the plan is to treat the last element as the top.

    • push appends to the vector.
    • pop removes the last element and returns it.
    • peek reads the last element without removing it.
    • size is the vector's length.

    Each method is one line that delegates to the matching Vec method. The work in this lesson is writing the signatures correctly: which methods change the stack, what they return, and how Option values are handled.

    Step by step

    1. Declare struct MyStack and its closing brace.
    2. Add the field data: Vec<i32>, a growable list of integers.
    3. Open impl MyStack, where the methods live.
    4. Write new, a function with no parameters that returns a MyStack. Rust has no special constructors; a function named new is the convention.
    5. Return MyStack { data: Vec::new() } as the last expression. Vec::new() is an empty vector.
    6. Write push's signature with &mut self, because it changes the stack, and a value: i32.
    7. Call the vector's own push on self.data.
    8. Write pop's signature: &mut self again, returning an i32.
    9. Return self.data.pop().unwrap(). The vector's pop returns an Option, which holds either a value or nothing, and unwrap takes the value out.
    10. Write peek's signature with plain &self, since it only looks.
    11. Return *self.data.last().unwrap(). last() gives a reference to the final element, and the * reads the number behind it.
    12. Write size's signature: &self, returning a usize.
    13. Return self.data.len().
    14. Write the driver. In mainFunction, create let mut s = MyStack::new();. It needs mut because pushing and popping change it. Then push 10, 20 and 30, and print with println!: the top, the size, a pop, the size, two more pops, the empty size, then push 7 and print the top and the size.

    The solution in Rust

    struct MyStack {
        data: Vec<i32>,
    }
    impl MyStack {
        fn new() -> MyStack {
            MyStack { data: Vec::new() }
        }
        fn push(&mut self, value: i32) {
            self.data.push(value);
        }
        fn pop(&mut self) -> i32 {
            self.data.pop().unwrap()
        }
        fn peek(&self) -> i32 {
            *self.data.last().unwrap()
        }
        fn size(&self) -> usize {
            self.data.len()
        }
    }
    fn mainFunction() {
        let mut s = MyStack::new();
        s.push(10);
        s.push(20);
        s.push(30);
        println!("Top: {}", s.peek());
        println!("Size: {}", s.size());
        println!("Pop: {}", s.pop());
        println!("Size: {}", s.size());
        println!("Pop: {}", s.pop());
        println!("Pop: {}", s.pop());
        println!("Empty size: {}", s.size());
        s.push(7);
        println!("Top: {}", s.peek());
        println!("Size: {}", s.size());
    }
    

    Language details

    • unwrap() and empty stacks. Both pop() and last() return None on an empty vector. unwrap() turns None into a panic. A program that pops an empty stack ends with:
    called `Option::unwrap()` on a `None` value
    

    The lesson's tests avoid this case. Checking size() == 0 before calling, or returning an Option<i32> instead of an i32, would be the safer designs.

    • Why the * in peek. Without it the compiler reports expected `i32`, found `&i32`, since last() returns an Option<&i32>. The star dereferences the reference. It is fine to copy here because i32 is a Copy type.
    • &mut self is required for push and pop. With plain &self, self.data.push(value) fails with cannot borrow `self.data` as mutable, as it is behind a `&` reference.
    • The return type of size is usize. len() returns a usize, so the method must too. It prints like any integer.
    • Method names don't clash with Vec. Inside MyStack::push, self.data.push(value) calls the Vec method on the field, not MyStack::push again.

    Watching the vector change

    Printing s.data after each operation of the driver shows that the top of the stack is always the right end of the vector:

    push 10 -> [10]
    push 20 -> [10, 20]
    push 30 -> [10, 20, 30]
    peek = 30 -> [10, 20, 30]
    pop = 30 -> [10, 20]
    pop = 20 -> [10]
    pop = 10 -> []
    push 7 -> [7] size 1
    

    Peeking leaves the vector untouched, while each pop shortens it by one element, always from the right. The values come out as 30, 20, 10: the reverse of the order they went in.

    Complexity

    Each operation is O(1). push is amortized O(1): occasionally the vector has to grow its buffer, but over many pushes the cost averages out to a constant. pop, peek and size are plain O(1). The stack uses O(n) space for n stored values.

    Taking the start of the vector as the top would be slow, because inserting or removing at index 0 shifts every other element.

    Edge cases and common mistakes

    • Peek must not remove. After peek the size is unchanged. Using pop inside peek would shrink the stack.
    • Order of evaluation in the driver. In println!("Pop: {}", s.pop()) the pop runs first, then the value is printed, so the following size is one smaller.
    • Reuse after emptying. After three pops the size is 0, and the stack still works: pushing 7 gives a top of 7 and a size of 1.
    • Forgetting mut on the variable. let s = MyStack::new(); fails as soon as you push.

    Key takeaways

    • A stack needs only the end of a Vec: push, pop and peek all work at that end.
    • Methods that change the struct take &mut self; readers take &self.
    • pop() and last() return an Option, and unwrap() panics if it is empty.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free