Go: Implement a stack (LIFO)
The idiomatic way to implement a stack in Go is to use a slice:
- to push you use the built-in
append
function, and - to pop you slice off the top element.
// 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!