Stacks from a Slice
A stack is a pile: you put things on top and take them off the top. The last thing in is the first thing out (LIFO, last in, first out). Undo in an editor, matching brackets, walking back out of a maze: whenever you need to "go back to the most recent one", reach for a stack.
A slice is already a stack
Go has no stack type, and doesn't need one. A slice does both jobs:
var stack []int
stack = append(stack, 4) // push
stack = append(stack, 8)
top := stack[len(stack)-1] // peek: 8
stack = stack[:len(stack)-1] // pop
Pushing and popping at the end of a slice are both O(1). Always check len(stack) > 0 before popping: reading stack[-1] panics.
A stack for any type
If you push and pop in several places, wrap the slice in a type. With generics one definition works for int, string, Point or anything else:
type Stack[T any] struct {
items []T
}
var history Stack[string]
var path Stack[Point]
T is a type parameter: Stack[string] is a stack whose T is string. Inside a method, var zero T gives you the zero value of whatever T is, which is handy for returning "nothing" from an empty stack.
Undo as a stack
Undo is the classic example. Before every change, push the current state. Undo pops the most recent state and restores it. A second undo pops the one before, and so on.
Task
This lesson's input is a list of commands for a tiny editor that starts with an empty text:
type <text>adds the text at the end (everything after the first space, spaces included);delete <n>removes the lastncharacters, or everything if there are fewer;undoreverts the most recenttypeordelete. With nothing to undo, it does nothing.
- Complete
PushandPoponStack[T].Popreturnsok == falsewhen the stack is empty. - Complete
edit(commands []string) (string, error): run the commands and return the final text. Return an error for an unknown command or adeletecount that isn't a whole number of zero or more.