Simple Stack

A stack is a collection where the last item you put in is the first one you take out — like a stack of plates. You add a plate on top (push), and you always remove from the top (pop). This is called last-in, first-out (LIFO).

Stacks show up everywhere: your browser's back button is a stack of visited pages, undo in a text editor is a stack of actions, and function calls in any program are managed with a call stack.

Go doesn't have a built-in stack type, but a slice does the job. Push with append, pop with slicing.

package main

import "fmt"

func main() {
	var stack []string

	// Push
	stack = append(stack, "first")
	stack = append(stack, "second")
	stack = append(stack, "third")
	fmt.Println("Stack:", stack)

	// Pop
	top := stack[len(stack)-1]
	stack = stack[:len(stack)-1]
	fmt.Printf("Popped: %s\n", top)
	fmt.Println("Stack:", stack)

	// Pop again
	top = stack[len(stack)-1]
	stack = stack[:len(stack)-1]
	fmt.Printf("Popped: %s\n", top)
	fmt.Println("Stack:", stack)
}
▶ Open Go Playground

Copy the code above and paste to run

© 2026 ByteLearn.dev. Free courses for developers. · Privacy