How to implement a stack in Golang
A stack is an ordered data structure that follows the Last-In-First-Out (LIFO) principle. Stacks are most easily implemented in Golang using slices:
- An element is pushed to the stack with the built-in
appendfunction. - The element is popped from the stack by slicing off the top element.
Code
An implementation of a stack is shown below:
package mainimport "fmt"type Stack []string// IsEmpty: check if stack is emptyfunc (s *Stack) IsEmpty() bool {return len(*s) == 0}// Push a new value onto the stackfunc (s *Stack) Push(str string) {*s = append(*s, str) // Simply append the new value to the end of the stack}// Remove and return top element of stack. Return false if stack is empty.func (s *Stack) Pop() (string, bool) {if s.IsEmpty() {return "", false} else {index := len(*s) - 1 // Get the index of the top most element.element := (*s)[index] // Index into the slice and obtain the element.*s = (*s)[:index] // Remove it from the stack by slicing it off.return element, true}}func main() {var stack Stack // create a stack variable of type Stackstack.Push("this")stack.Push("is")stack.Push("sparta!!")for len(stack) > 0 {x, y := stack.Pop()if y == true {fmt.Println(x)}}}
Explanation
- A
typeis made for a list calledStack. This allows us to create methods onStack, just like the methods of a class. - The
PushandPopmethods are implemented on lines and , respectively. ThePopmethod utilizes theIsEmptyhelper function to cater to the exception that occurs when the stack is empty. - In the
mainfunction, the stack is populated with three strings. The values stacked in the stack are then popped, notice the order in which they are printed. The output confirms that the stack correctly follows the LIFO principle.
Note that the stack is initialized to contain strings. Changing the type to
interface{}would allow the stack to work for any data type.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved