Function types, literals, and method values
Functions in Go are first-class values, but closures, method values, and method expressions capture different semantics.
Canonical guidance
- function literals close over surrounding variables
- a method value binds a receiver now
- a method expression produces a function that still expects the receiver argument
Use when
- passing callbacks
- explaining closure capture
- adapting methods to higher-order APIs
Avoid
- assuming a closure snapshots values automatically
- confusing
v.MwithT.M - hiding large mutable captured state in callbacks
Preferred pattern
next := srv.ServeHTTP
Anti-pattern
- using a closure over loop variables without checking what value later execution will observe
Explanation: This is tempting because the code looks local, but closures capture variables, not magic immutable snapshots.
Why
- many subtle callback bugs come from closure and method-binding semantics rather than control-flow style