How to implement a stack in Go

Rodrigo Ancavil
2 min readSep 25, 2023

--

We are going to implement a generic stack in Go, which means that the stack could store any type of item. To do that we’ll use the Go empty interface (a empty interface may hold values of any type).

You can check the code here.

Creating the workspace

$ mkdir Stack
$ cd Stack
$ go mod init data/datastructure
$ go work use .
$ mkdir stack
Stack/
stack/
go.mod

Writing the code

Create the stack.go file in the Stack/stack directory, and write the following code. We’ll implement the methods Pop() (to remove the last item from Stack)and Push() (to add an item to the top of the Stack).

package stack

type Stack []interface{}

func (stack *Stack) Pop() {
*stack = (*stack)[:len(*stack)-1]
}

func (stack *Stack) Push(elem interface{}) {
*stack = append(*stack, elem)
}

We have created a type called Stack which consists in an slice of empty interfaces, in this way we can store any kind of item (integers, floats, strings, and so on).

Using our Stack

Create the main.go file in the Stack directory. We’ll create a program using Stack from the package data/datastructures/stack with integer (nums) items and string (names) items.

package main

import (
"data/datastructures/stack"
"fmt"
)

func main() {
nums := stack.Stack{}

for i := 0; i < 10; i++ {
nums.Push(i + 1)
}

for _, num := range nums {
fmt.Printf("%T, %d\n", num, num)
}

fmt.Println(nums)

names := stack.Stack{}

names.Push("Robert")
names.Push("Fred")
names.Push("Alicia")
fmt.Println(names)

for _, name := range names {
fmt.Printf("%T, %s\n", name, name)
}

names.Pop()

fmt.Println(names)
}

Execute the following command inside Stack directory where you wrote the main.go file.

$ go run main.go

int, 1
int, 2
int, 3
int, 4
int, 5
int, 6
int, 7
int, 8
int, 9
int, 10
[1 2 3 4 5 6 7 8 9 10]
[Robert Fred Alicia]
string, Robert
string, Fred
string, Alicia
[Robert Fred]

You should get the following output:

int, 1
int, 2
int, 3
int, 4
int, 5
int, 6
int, 7
int, 8
int, 9
int, 10
[1 2 3 4 5 6 7 8 9 10]
[Robert Fred Alicia]
string, Robert
string, Fred
string, Alicia
[Robert Fred]

Getting the Code

You can get the complete code from github here.

$ git clone https://github.com/rancavil/go-stack.git
$ cd go-stack
$ go work use .

You can execute the test to check out how stack works.

$ cd go-stack/stack
$ go test -v
=== RUN TestPop
=== RUN TestPop/Test-Pop-0
=== RUN TestPop/Test-Pop-1
=== RUN TestPop/Test-Pop-2
--- PASS: TestPop (0.00s)
--- PASS: TestPop/Test-Pop-0 (0.00s)
--- PASS: TestPop/Test-Pop-1 (0.00s)
--- PASS: TestPop/Test-Pop-2 (0.00s)
=== RUN TestPush
=== RUN TestPush/Test-Push-0
=== RUN TestPush/Test-Push-1
--- PASS: TestPush (0.00s)
--- PASS: TestPush/Test-Push-0 (0.00s)
--- PASS: TestPush/Test-Push-1 (0.00s)
PASS
ok data/datastructures/stack 0.587s

--

--

Rodrigo Ancavil
Rodrigo Ancavil

Written by Rodrigo Ancavil

IT Architect and Software Engineer

No responses yet