Section 4 of 11
Closures
Functions are values, they capture variables, and they replace most small classes.
A closure captures the variable itself, not a copy of it, and keeps it alive after the enclosing function returns. Java forces captured locals to be effectively final; Go does not. This is why Go uses closures where Java would use a small stateful class.
The closure is the object; captured vars are the fields
go.dev playground
Try it: Call counter() twice into two variables — each closure gets its own independent `count`.
Stack three of these and you have the HTTP middleware pattern: an outer function captures config, the middle captures the next handler, and the inner one runs per request.
func WithTimeout(d time.Duration) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler { // captures d
return http.HandlerFunc(func(w, r) { // captures d AND next
... // runs per request
})
}
}