liveBook · Manning

Lambda

As explained in 100 Go Mistakes and How to Avoid Them

An anonymous function is a function defined without an explicit name.

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

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains closure capture through configuration and goroutine examples, and traces deferred error propagation with named results.
Examples
Uses rows.Close error handling and goroutines over loop values to demonstrate practical closure behavior.
What you can do after
Apply anonymous functions to deferred cleanup and functional options, or avoid loop-variable capture by snapshotting or passing values.
How it connects
Connects closures with functional options, defer, named result parameters, error handling, goroutines, and loop variables.

Also explained in

Compare how 18 books explain lambda →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.