A Go anonymous function is defined without a name. When it refers to variables outside its body, it is also a closure. Anonymous functions can handle deferred cleanup, configure APIs, or run in goroutines. section 7.7 section 2.11.3
Watch for these practical behaviors:
- A deferred anonymous function can inspect a cleanup error and update a named result. Returning from that function does not return from the enclosing function. section 7.7
- A functional option can return a closure that captures a setting such as port, validates it, and later updates configuration. section 2.11.3
- A goroutine closure that reads a loop variable may observe its changing value. Capture a per-iteration local value or pass the value as a function argument. section 9.3
defer func() {
closeErr := rows.Close() #1
if err != nil { #2
if closeErr != nil {
log.Printf("failed to close rows: %v", err)
}
return
}
err = closeErr #3
}()
This deferred closure preserves an earlier error and uses the close error only when no earlier error exists. section 7.7
for _, i := range s {
go func(val int) { #1
fmt.Print(val)
}(i) #2
}
Passing the loop value as an argument gives each goroutine its own input instead of capturing the changing loop variable. section 9.3

















