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 append function.
  • The element is popped from the stack by slicing off the top element.
svg viewer

Code

An implementation of a stack is shown below:

package main
import "fmt"
type Stack []string
// IsEmpty: check if stack is empty
func (s *Stack) IsEmpty() bool {
return len(*s) == 0
}
// Push a new value onto the stack
func (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 Stack
stack.Push("this")
stack.Push("is")
stack.Push("sparta!!")
for len(stack) > 0 {
x, y := stack.Pop()
if y == true {
fmt.Println(x)
}
}
}

Explanation

  • A type is made for a list called Stack. This allows us to create methods on Stack, just like the methods of a class.
  • The Push and Pop methods are implemented on lines 121412-14 and 172617-26, respectively. The Pop method utilizes the IsEmpty helper function to cater to the exception that occurs when the stack is empty.
  • In the main function, 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 ©2024 Educative, Inc. All rights reserved