Start learning free

LESSON 65 OF 69 · PROJECTS: OBJECT-ORIENTED

Stack Impl in Go: Building MyStack with a Slice

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 []int slice inside type MyStack struct and offers four operations.

The methods:

  • func (stack *MyStack) push(value int)
  • func (stack *MyStack) pop() int
  • func (stack MyStack) peek() int
  • func (stack MyStack) size() int

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 Go, indexing an empty slice panics.)

You start with: The starter already contains the code that uses your stack (below).

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()))

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.

Go has no classes: the struct holds the data and methods are functions with a receiver. push and pop change the slice, so they use a pointer receiver (*MyStack). Use append to add and stack.data[:len(stack.data)-1] to drop the last element.

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)
}

STEP 1 OF 12
    Ctrl + Enter to check

    GO · PROJECTS: OBJECT-ORIENTED

    Stack Impl in Go, 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: 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() int removes the top value and returns it.
    • peek() int returns the top value and leaves it in place.
    • size() int says 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

    1. Declare MyStack as a struct with one field, data, a slice of int.
    2. Write push with a pointer receiver. A value receiver would append to a copy of the struct, and the caller's stack would stay empty.
    3. Append and store the result. append returns the longer slice, which may live in a new array, so the result goes back into stack.data.
    4. Write pop, also with a pointer receiver, since it shortens the stored slice.
    5. Save the top. Read stack.data[len(stack.data)-1] into top before anything is removed.
    6. Cut the last element off. stack.data[:len(stack.data)-1] keeps all but the last item. Assign it back to stack.data.
    7. Return top.
    8. Write peek with a plain receiver. It changes nothing, so a copy is enough.
    9. Return the last element without cutting anything.
    10. Write size, again with a plain receiver, and return len(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 push had the receiver (stack MyStack), it would append to the copy's data field and the original would never grow. With a value receiver, calling push(1) on an empty stack leaves len(v.data) at 0.
    • Calling pointer methods on a value. stack := MyStack{} is a plain value, yet stack.push(10) works. Because stack is a variable, Go takes its address automatically.
    • The zero value is ready to use. MyStack{}, or var z MyStack, has a nil slice with length 0. append works on a nil slice, and size() 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 later push overwrites it. After pushing 1, 2 and 3 and popping, data is [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. push and pop use *MyStack, while peek and size use MyStack. 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 an int to a string on its own. strconv.Itoa(30) gives "30". The code needs both fmt and strconv imported, 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)-1 is -1, and the program panics with runtime error: index out of range [-1]. The lesson's tests never do this. A stack for real use would check size() == 0 first or return a second bool value.
    • A value receiver on push or pop. The code compiles but the changes are lost, because they apply to a copy.
    • Not storing the result of append. Writing append(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 why pop saves top first.
    • 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.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free