1min.

1MIN · GO

Go’s defer rules explain why cleanup belongs next to acquisition

Go’s defer schedules cleanup for the surrounding function’s exit, including when a later error causes an early return. Arguments are captured when the defer is registered, and deferred calls run in reverse order. This older official guide also explains panic and recover: recovery belongs in a deferred function, while a package’s public API should still normally expose explicit error returns.

The Go Team · Aug 4, 2010

Why it matters

The rules prevent subtle cleanup and captured-value mistakes that remain relevant in everyday Go.

More context

Revisit this foundational 2010 guide and trace its short examples before reading the output. Placing a deferred close immediately after a successful open makes later return paths easier to review.

Keep in mind

The examples teach control flow rather than a complete production file-copy implementation, including handling close errors.

Original read

More engineering ideas, one minute at a time.

Explore more stories