Recursion
A recursive function calls itself (or a partner function) on a smaller piece of the problem until it hits a base case. Each call has its own stack frame.
Detailed Explanation
Walking a directory tree, evaluating an expression, or searching a graph by DFS are naturally recursive: the problem is the same shape as a piece of itself. You write the base case first (if n == 0 { return 1 }), then the step that calls the function on a smaller n or a child node.
Go has no tail-call elimination. A "tail recursive" loop still consumes a frame per call. A chain of n calls uses O(n) stack. Goroutine stacks grow, but a recursion of millions of frames will crash. For unbounded depth, use an explicit []T as a stack and a loop.
Closures can recurse. var walk func(n *Node); walk = func(n *Node) { ... walk(n.Left) } is the form when you want a nested helper that closes over a visitor. Declare walk before assigning, or the inner name is not in scope.
Mutual recursion (parseExpr calls parseTerm calls parseExpr) is fine. Keep a depth limit or a remaining-token check so a malformed input cannot recurse forever.
When not to recurse. Fibonacci without memoization is exponential time. A linear scan of a slice should be a for. Recursion is for trees, graphs, divide-and-conquer, and backtracking, not for "I can write a loop as a function call."
What it costs. Each frame holds parameters, locals, and return info. A large [4096]byte local in a recursive function multiplies that by depth and will blow the stack quickly. Keep recursive locals small. Extra heap from escaping closures is a separate cost.
Code Examples
package main
import "fmt"
func fact(n int) int {
if n < 2 {
return 1
}
return n * fact(n-1)
}
func main() {
fmt.Println(fact(5)) // 120
}type Node struct {
Val int
Left, Right *Node
}
func sum(n *Node) int {
if n == nil {
return 0
}
return n.Val + sum(n.Left) + sum(n.Right)
}func walkIter(root *Node, visit func(int)) {
var st []*Node
if root != nil {
st = append(st, root)
}
for len(st) > 0 {
n := st[len(st)-1]
st = st[:len(st)-1]
visit(n.Val)
if n.Right != nil {
st = append(st, n.Right)
}
if n.Left != nil {
st = append(st, n.Left)
}
}
}Common Gotchas
Missing or wrong base case loops until stack overflow
always handle `nil` nodes and `n == 0`.
Deep recursion can crash a goroutine
prefer an explicit stack when depth is user-controlled.
A large local in a recursive function multiplies stack use
allocate big buffers on the heap (`make`) if you must have them.
There is no `goto` substitute required
a loop plus a slice is the iterative form.