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: last in, first out, like a pile of plates. The lesson asks for a MyStack type that stores whole numbers in a slice, data []int, and offers four operations:
push(value int)puts a value on top and returns nothing.pop() intremoves the top value and returns it.peek() intreturns the top value and leaves it in place.size() intsays how many values are stored. A new stack has size 0.
The driver pushes 10, 20 and 30. The top is then 30 and the size is 3. Popping gives 30, 20 and 10 in that order. The stack is empty (size 0), and after pushing 7 the top is 7 and the size is 1. The lesson's tests never call pop or peek on an empty stack.
Approach: the top is the end of the slice
A stack needs fast work at one end only, so the natural choice is the end of a slice. Adding there is cheap, and so is removing the last element. Putting the top at the front would force every element to shift on each push and pop.
So the layout is simple. The last element of data is the top, the index of the top is len(stack.data) - 1, and the size is just len(stack.data).
Go has no classes. A struct holds the data, and methods are functions declared with a receiver, the part in brackets before the method name. The receiver kind matters here: methods that change the stack must receive a pointer.
Step by step
- Declare
MyStackas a struct with one field,data, a slice ofint. - Write
pushwith a pointer receiver. A value receiver would append to a copy of the struct, and the caller's stack would stay empty. - Append and store the result.
appendreturns the longer slice, which may live in a new array, so the result goes back intostack.data. - Write
pop, also with a pointer receiver, since it shortens the stored slice. - Save the top. Read
stack.data[len(stack.data)-1]intotopbefore anything is removed. - Cut the last element off.
stack.data[:len(stack.data)-1]keeps all but the last item. Assign it back tostack.data. - Return
top. - Write
peekwith a plain receiver. It changes nothing, so a copy is enough. - Return the last element without cutting anything.
- Write
size, again with a plain receiver, and returnlen(stack.data).
The remaining part of the file is the driver, mainFunction, which is already written for you. It uses strconv.Itoa to turn each integer into text, so it can join it to a label with +.
The solution in Go
type MyStack struct {
data []int
}
func (stack *MyStack) push(value int) {
stack.data = append(stack.data, value)
}
func (stack *MyStack) pop() int {
top := stack.data[len(stack.data)-1]
stack.data = stack.data[:len(stack.data)-1]
return top
}
func (stack MyStack) peek() int {
return stack.data[len(stack.data)-1]
}
func (stack MyStack) size() int {
return len(stack.data)
}
func mainFunction() {
stack := MyStack{}
stack.push(10)
stack.push(20)
stack.push(30)
fmt.Println("Top: " + strconv.Itoa(stack.peek()))
fmt.Println("Size: " + strconv.Itoa(stack.size()))
fmt.Println("Pop: " + strconv.Itoa(stack.pop()))
fmt.Println("Size: " + strconv.Itoa(stack.size()))
fmt.Println("Pop: " + strconv.Itoa(stack.pop()))
fmt.Println("Pop: " + strconv.Itoa(stack.pop()))
fmt.Println("Empty size: " + strconv.Itoa(stack.size()))
stack.push(7)
fmt.Println("Top: " + strconv.Itoa(stack.peek()))
fmt.Println("Size: " + strconv.Itoa(stack.size()))
}
The driver prints:
Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1
The Go details worth knowing:
- Pointer receivers for changes. If
pushhad the receiver(stack MyStack), it would append to the copy'sdatafield and the original would never grow. With a value receiver, callingpush(1)on an empty stack leaveslen(v.data)at 0. - Calling pointer methods on a value.
stack := MyStack{}is a plain value, yetstack.push(10)works. Becausestackis a variable, Go takes its address automatically. - The zero value is ready to use.
MyStack{}, orvar z MyStack, has anilslice with length 0.appendworks on anilslice, andsize()returns 0, so no constructor is needed. - Slicing doesn't erase.
stack.data[:n-1]is a shorter view of the same backing array. The popped value stays in the array until a laterpushoverwrites it. After pushing 1, 2 and 3 and popping,datais[1 2], and pushing 9 gives[1 2 9]in the same space. For a stack of integers this is harmless. For a stack of pointers you would clear the slot first so the garbage collector could free the value. - Mixed receivers.
pushandpopuse*MyStack, whilepeekandsizeuseMyStack. Both kinds work on the same type. A value receiver copies only the slice header (pointer, length and capacity), not the elements, so the copy is cheap. strconv.Itoa. The driver builds strings with+, and Go does not convert anintto a string on its own.strconv.Itoa(30)gives"30". The code needs bothfmtandstrconvimported, and an unused import is a compile error.
Complexity
Time: push is amortized O(1). Most appends write into spare capacity, and the occasional append that must grow the array copies the elements into a bigger one, so the cost averages out. pop, peek and size are O(1) because each does a fixed amount of work: an index, a reslice or a length read.
Space: O(n) for n stored values. Each operation needs only a few extra variables.
Edge cases and common mistakes
- Popping or peeking when empty. The index
len(stack.data)-1is -1, and the program panics withruntime error: index out of range [-1]. The lesson's tests never do this. A stack for real use would checksize() == 0first or return a secondboolvalue. - A value receiver on
pushorpop. The code compiles but the changes are lost, because they apply to a copy. - Not storing the result of
append. Writingappend(stack.data, value)alone is a compile error in Go, because the result is unused, but assigning it to a throwaway variable is a silent bug. - Returning the top after cutting. If you reslice first and read
stack.data[len(stack.data)-1]afterwards, you return the wrong element. That is whypopsavestopfirst. - Off-by-one in the slice bound.
[:len(stack.data)-1]drops exactly one element.[:len(stack.data)]drops none, and[1:]removes the bottom of the stack instead of the top. - Reusing the stack after it empties. Pushing again works, because an empty slice is still a valid slice. The driver checks this with its final
push(7).
Key takeaways
- Use the end of a slice as the top of the stack, so every operation is cheap.
- Methods that change the struct need pointer receivers; read-only methods can use value receivers.
- Always store the result of
append. - Reslicing with
s[:len(s)-1]removes the last element without copying.
