A basic stack (LIFO) data structure


The idiomatic way to implement a stack data structure in Go is to use a slice:

var stack []string

stack = append(stack, "world!") // Push
stack = append(stack, "Hello ")

for len(stack) > 0 {
    n := len(stack) - 1 // Top element

    stack = stack[:n] // Pop
Hello world!


Appending a single element to a slice takes constant amortized time. See Amortized time complexity for a detailed explanation.

If the stack is permanent and the elements temporary, you may want to remove the top element before popping the stack to avoid memory leaks.

// Pop
stack[n] = "" // Erase element (write zero value)
stack = stack[:n]

More code examples

Go blueprints: code for com­mon tasks is a collection of handy code examples.

Share this page: