/golang:go-defer-panic-recoverfrom golang
Guides Go's defer, panic, and recover — the LIFO ordering and arguments-evaluated-at-the-defer-statement semantics, why defer is near-free since open-coded defers (so don't avoid it except in tight loops), the loop-defer handle-leak pitfall, panic only for programmer bugs and unrecoverable states (not ordinary failure), and recover only inside a deferred function at a boundary to convert a panic into an error. Auto-invokes when writing or editing defer, panic, recover, or deferred cleanup, and on "why does this defer run in the wrong order", "should this panic", or "how do I stop a panic from crashing the process". Routes ordinary error-as-value handling to go-error-handling.
Ships in golang. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
"Deferred function calls are executed in Last In First Out order after the surrounding function returns." · "A deferred function's arguments are evaluated when the defer statement is evaluated." — Defer, Panic, and Recover (Go blog)
"Don't use panic for normal error handling. Use error and multiple return values." — Go Code Review Comments — Don't Panic
defer, panic, and recover are three small mechanisms with sharp edges. defer is the everyday one — get its evaluation timing and loop behavior right. panic and recover are the rare ones — used for ordinary failure they turn Go into a worse exception language. This skill owns the mechanics and policy; ordinary errors-as-values route to go-error-handling.
defer Actually DoesFour facts, each load-bearing:
defer runs first.defer statement. "A deferred function's arguments are evaluated when the defer statement is evaluated" (Go blog) — not when the call later runs. This is the classic gotcha (Section 3).defer is the right place for cleanup — it fires on every return path, including a panic.Close-error capture (owned by go-error-handling).The everyday payoff: "Deferring a call to Close ... guarantees you will never forget to close the file ... [and] the close sits near the open, which is much clearer than placing it at the end" (Effective Go).
| Rule | The discipline | Source |
|---|---|---|
defer is for cleanup | Put release next to acquire; it runs on every return path | "an effective way to handle resource cleanup regardless of which return path is taken" (Effective Go) |
Args bind at the defer line | Don't expect a deferred arg to read a later value | "arguments are evaluated when the defer statement is evaluated" (Go blog) |
Don't defer in a loop for per-iteration cleanup | Close in the loop body or extract a function | Loop-defer accumulates until the function returns (Section 4) |
defer is not a perf concern | Near-zero overhead since Go 1.14 open-coded defers | "improves the performance of most uses of defer to incur almost zero overhead" (Go 1.14) |
panic is for bugs, not failure | Ordinary failures return an error | "Don't use panic for normal error handling" (CodeReviewComments) |
recover only in a deferred func | Anywhere else it returns nil and does nothing | "Recover is only useful inside deferred functions" (Go blog) |
| Recover only at a boundary | Convert a panic to an error; re-panic what you can't handle | "regains control of a panicking goroutine" (Go blog) |
defer StatementThe single most common defer surprise: the deferred call's arguments are snapshotted when defer runs, even though the call runs at return.
// WRONG — expecting start to be re-read at return; it is captured as the start value
func timed() {
start := time.Now()
defer log.Printf("took %v", time.Since(start)) // time.Since(start) runs NOW, logging ~0
doWork()
}
// RIGHT — defer a closure so the expression runs at return time
func timed() {
start := time.Now()
defer func() { log.Printf("took %v", time.Since(start)) }()
doWork()
}
The argument form evaluates time.Since(start) immediately; the closure form defers the whole expression. The same fact makes LIFO observable: for i := 0; i < 5; i++ { defer fmt.Printf("%d ", i) } "Prints: 4 3 2 1 0" (Effective Go) — each i is captured at its iteration, then the calls run in reverse.
defer fires at function return, not at the end of the loop body. Deferring Close inside a for accumulates open handles for the whole function — a file-descriptor leak that only shows up under load.
// WRONG — every file stays open until processAll returns; thousands of names => fd exhaustion
func processAll(names []string) error {
for _, name := range names {
f, err := os.Open(name)
if err != nil {
return err
}
defer f.Close() // does NOT close at end of iteration
use(f)
}
return nil
}
// RIGHT — extract the body so defer fires per item
func processAll(names []string) error {
for _, name := range names {
if err := processOne(name); err != nil {
return err
}
}
return nil
}
func processOne(name string) error {
f, err := os.Open(name)
if err != nil {
return err
}
defer f.Close() // fires at processOne's return — once per item
use(f)
return nil
}
Note the inverse: in a non-loop function, don't avoid defer for performance. Open-coded defers (Go 1.14) made it "incur almost zero overhead" (Go 1.14); Uber's guide agrees it "has an extremely small overhead and should be avoided only if you can prove that your function execution time is in the order of nanoseconds" (Uber Go Style Guide).
panic Is for Programmer Errors, Not Ordinary Failurepanic unwinds the stack and, unrecovered, crashes the process. Reserve it for bugs and truly unrecoverable states: a violated invariant, an impossible switch case, a nil that the code's own contract forbids. Ordinary, foreseeable failure — bad input, a missing file, a failed lookup — is an error the caller decides about. "Don't use panic for normal error handling. Use error and multiple return values" (CodeReviewComments); the Google style guide repeats it: "Do not use panic for normal error handling. Instead, use error and multiple return values" (Google Go Style Guide).
Legitimate uses are narrow: an init that cannot establish a required invariant — "panic is reasonable during initialization if the library cannot set itself up" (Effective Go) — or a MustCompile-style helper for compile-time-constant input. The depth of returning errors instead (wrapping, errors.Is/As, named-return decoration) is owned by go-error-handling.
recover Only in a Deferred Func, Only at a Boundary"Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions. During normal execution, a call to recover will return nil and have no other effect" (Go blog). So recover does something only when (a) it sits in a deferred function and (b) a panic is in flight. Use it at a boundary — the top of a request handler, or a goroutine you own — to convert a panic into an error rather than crash, then re-establish invariants.
// RIGHT — a boundary converts a panic into an error via a named return
func safeInvoke(fn func()) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered: %v", r) // re-establish: a panic is now an error
}
}()
fn()
return nil
}
// WRONG — recover outside a deferred func: returns nil, catches nothing, fn's panic still crashes
func brokenGuard(fn func()) {
if r := recover(); r != nil { // never true here
log.Println(r)
}
fn()
}
// WRONG — swallowing the panic with no log and no re-raise: the bug vanishes silently
func swallow(fn func()) {
defer func() { recover() }()
fn()
}
Two non-negotiables:
recover that catches every value and discards it hides real bugs. Inspect the recovered value; if it is not one you can turn into a clean error, log it and panic(r) again.recover only catches a panic in its own goroutine. "if do(work) panics, the error is logged and the goroutine exits cleanly without killing other goroutines" (Effective Go) — but a panic in a goroutine you spawned without its own recover crashes the whole program. Wrap each goroutine you own. See go-concurrency-goroutines.recover is not general control flow. Don't use panic/recover as exceptions to jump across ordinary call layers — that is the exception-language anti-pattern go-idiomatic-discipline bans.
The author never feels it at write time; someone downstream does:
defer f.Close() inside a for that never closed until the long-lived function returned (Section 4).defer func(){ recover() }() silently swallowed three layers down — no log, no re-raise, no trace (Section 6).defer/panic/recover done well is invisible; done badly it is a 3am page or a corrupted-state mystery.
This skill owns defer/panic/recover mechanics and policy. Adjacent depth lives elsewhere:
go-idiomatic-discipline — the policy root: "don't panic for ordinary failure" is one of its headline floor rules; panic-as-exceptions is one of its named anti-patterns.go-error-handling — errors as values: %w wrapping, errors.Is/As, and the defer-based named-return error decoration and Close-error-capture idioms (this skill teaches the defer/named-return mechanism; that skill teaches the error idiom built on it). Return an error instead of panicking — owned there.go-concurrency-goroutines — a panic in a goroutine you spawned without its own deferred recover crashes the process; wrap every goroutine you own.go-context — cancellation and defer cancel(); a recover boundary often sits at the same request edge where a context is derived.High-frequency defer/panic/recover anti-patterns in LLM-generated Go, each with wrong/right code and citations:
Source provenance for every claim in this skill:
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
25 skills in this plugin
/go-channels-selectGuides Go channel mechanics — declare directionality in signatures (chan less than - send-only, less than -chan receive-only), let only the sender close and only when sends are done (closing is a broadcast, not cleanup), read the comma-ok / range-ends-on-close idiom so a closed channel's zero value is not mistaken for data, choose unbuffered (synchronization) vs buffered (decoupling) deliberately, use chan struct{} for pure signals, and drive select with default for non-blocking and the nil-channel trick to disable a case. Auto-invokes when writing or editing channels, chan declarations, close(), select statements, or buffered channels, and on "send on closed channel panic" / "why does this select block" / "why does my range over a channel never end" requests. The depth behind the policy root's "don't fight Go" for the communication primitive./go-concurrency-goroutinesGuides goroutine lifetime and ownership — never start a goroutine you can't stop, give every goroutine a defined exit (context cancellation, a closed channel, or bounded work), avoid the blocked-forever leak, use sync.WaitGroup correctly (Add before the go, or wg.Go in 1.25) and golang.org/x/sync/errgroup for fallible fan-out and SetLimit worker pools, and keep library functions synchronous so the caller owns concurrency. Auto-invokes when writing or editing `go` statements, goroutines, sync.WaitGroup, errgroup, worker pools, or on "is this goroutine leaking" / "how do I wait for these" requests. The depth behind the policy root's "never start a goroutine you can't stop."/go-contextGuides Go context.Context discipline — pass it as the first parameter named ctx and never store it in a struct, derive children with WithCancel/WithTimeout/WithDeadline and ALWAYS defer cancel() (go vet's lostcancel flags a missing one), check ctx.Done()/ctx.Err() in loops and before expensive work, start from context.Background() at entry points and context.TODO() when you don't have one yet, attach reasons with WithCancelCause/Cause and decouple with WithoutCancel/AfterFunc (1.20/1.21), and carry only request-scoped values behind an unexported key type. Auto-invokes when writing or editing functions taking context.Context, WithCancel/WithTimeout/WithValue, ctx.Done()/Err(), or on "where should ctx go" / "is this context leaking" requests. The propagation-and-cancellation depth behind the policy root's "never start a goroutine you can't stop."/go-error-handlingGuides Go error handling as values — wrap with fmt.Errorf and %w to preserve the chain, inspect with errors.Is (sentinel) and errors.As / errors.AsType (typed) instead of string-matching, choose sentinel vs custom error types and when they become API, combine with errors.Join, write lowercase un-punctuated messages, handle each error exactly once, and decorate or close-with-error via named returns and defer. Auto-invokes when writing or editing error returns, fmt.Errorf, errors.Is/As, custom error types, or on "handle this error" / "why is this error not matching" requests. The depth behind the policy root's "errors are values, never silently discarded."/go-genericsGuides Go generics restraint and constraint design — reach for a type parameter only when you would otherwise write the exact same code for multiple types (a container, or an algorithm over a slice/map/channel element type like map/filter/reduce), never when you only call a method on the value (that is an interface), and prefer the stdlib slices/maps/cmp helpers over hand-rolled generics. Covers constraints (any, comparable, cmp.Ordered, the ~T underlying-type element, unions like int | int64), type inference, generic type aliases (1.24), and self-referential constraints (1.26). Auto-invokes when writing or editing type parameters ([T any]), type constraints, generic functions or types, and on "should this be generic", "generic or interface here", or "make this generic". A type parameter earns its place only on real duplication; clarity first./go-idiomatic-disciplineGuides core Go authoring discipline along two axes — handle errors honestly and stop fighting the language on the floor (no discarded errors, no panic for ordinary failure, no Java/Python-in-Go), and don't over-abstract or out-clever it on the ceiling (no interface-per-struct, no premature generics, no framework scaffolding for a small tool). The judgment target is "clear AND correct." Auto-invokes when writing or editing .go files, and on "make it idiomatic", "is this idiomatic Go", or "clean this up" requests. The dual-axis policy root every other Go skill routes back to.npx claudepluginhub ctoth/golang-skills-plugin --plugin golang