liveBook · Manning

Closure

As explained in Go in Practice, Second Edition

A closure is a function value that retains access to variables from its enclosing lexical scope.

A closure is a function that can access variables in its enclosing scope. In Go, an anonymous closure is useful when deferred work needs local state—for example, when handling a panic before a function returns. section 4.3.4

Recover and read updated state

```go package main import "fmt" func main() { var msg string defer func() { if err := recover(); err != nil { fmt.Println("recovered:", err) } fmt.Println(msg) }() msg = "ready" panic("failure") } ``` The trailing `()` supplies the call, but `defer` delays execution. The closure reads `msg` after its value changes and calls `recover` while handling the panic. Declare `msg` before the closure: a variable first declared afterward is not in its scope. section 4.3.4

Closures also help with goroutine helpers that accept a no-argument function: the function can access variables already in scope without adding parameters to the helper’s function type. Shared access can introduce race conditions; use `go run -race` or `go build -race` when checking concurrent code. section 4.3.5

Listing 4.23 Panics in goroutines
package safely

import (
     "log"
)

type GoDoer func()          #1
func Go(todo GoDoer) {          #2
     go func() {                 #3
            defer func() {
                   if err := recover(); err != nil {      #4
                           log.Printf("Panic in safely    #4
                           .Go: %s", err)                 #4
                   }                                      #4
            }()                                           #4
            todo()    #5
     }()
}

A small `GoDoer` wrapper shows an anonymous function starting a goroutine and a deferred closure recovering and logging its panic. section 4.3.5

How Go in Practice, Second Edition covers it

How deep it goes
Explains deferred anonymous-function syntax and variable scope through working examples, without developing closure internals.
Examples
Shows deferred recovery, a variable changed before deferred execution, and a goroutine wrapper that traps panics.
What it assumes
Assumes basic Go functions and variables while demonstrating deferred closure syntax and its scope.
What you can do after
Build it from scratch using deferred closures to recover panics, or pass captured state to a goroutine helper.
How it connects
Connects closures to defer, recover, panic, goroutines, function types, and race conditions.

Also explained in

Compare how 20 books explain closure →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.