Go: Implement a stack (LIFO)

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

// Create
var stack []string

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

for len(stack) > 0 {
        // Print top
        n := len(stack) - 1
        fmt.Print(stack[n])

        // Pop
        stack = stack[:n]
}
// Output: 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] = "" // to avoid memory leak
stack = stack[:n]
…

Comments

Be the first to comment!