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) -> i32removes the top value and returns it.peek(&self) -> i32returns the top value and leaves it in place.size(&self) -> usizereturns 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.
pushappends to the vector.popremoves the last element and returns it.peekreads the last element without removing it.sizeis 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
- Declare
struct MyStackand its closing brace. - Add the field
data: Vec<i32>, a growable list of integers. - Open
impl MyStack, where the methods live. - Write
new, a function with no parameters that returns aMyStack. Rust has no special constructors; a function namednewis the convention. - Return
MyStack { data: Vec::new() }as the last expression.Vec::new()is an empty vector. - Write
push's signature with&mut self, because it changes the stack, and avalue: i32. - Call the vector's own
pushonself.data. - Write
pop's signature:&mut selfagain, returning ani32. - Return
self.data.pop().unwrap(). The vector'spopreturns anOption, which holds either a value or nothing, andunwraptakes the value out. - Write
peek's signature with plain&self, since it only looks. - Return
*self.data.last().unwrap().last()gives a reference to the final element, and the*reads the number behind it. - Write
size's signature:&self, returning ausize. - Return
self.data.len(). - Write the driver. In
mainFunction, createlet mut s = MyStack::new();. It needsmutbecause pushing and popping change it. Then push 10, 20 and 30, and print withprintln!: 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. Bothpop()andlast()returnNoneon an empty vector.unwrap()turnsNoneinto 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
*inpeek. Without it the compiler reportsexpected `i32`, found `&i32`, sincelast()returns anOption<&i32>. The star dereferences the reference. It is fine to copy here becausei32is aCopytype. &mut selfis required forpushandpop. With plain&self,self.data.push(value)fails withcannot borrow `self.data` as mutable, as it is behind a `&` reference.- The return type of
sizeisusize.len()returns ausize, so the method must too. It prints like any integer. - Method names don't clash with
Vec. InsideMyStack::push,self.data.push(value)calls theVecmethod on the field, notMyStack::pushagain.
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
peekthe size is unchanged. Usingpopinsidepeekwould 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 followingsizeis 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
muton 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()andlast()return anOption, andunwrap()panics if it is empty.
