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



















