A basic stack (LIFO) data structure

yourbasic.org/golang

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
    fmt.Print(stack[n])

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

Watch out for memory leaks

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

// 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: