Code-Memo

Defer, panic, and recovery

Python’s with maps loosely to defer for cleanup, and panic/recover in rare cases — not for normal error handling.

defer

defer schedules a function call for when the surrounding function returns (LIFO order).

f, err := os.Open("file.txt")
if err != nil {
	return err
}
defer f.Close()

Arguments to deferred calls are evaluated immediately; the call runs later.

defer in loops

Calling defer inside a tight loop can grow the defer stack until the function returns. For loops, often use an inline closure or explicit Close() at the end of each iteration.

panic

Stops normal execution and unwinds the stack until a recover in a deferred function on that goroutine runs, or the program crashes.

recover
func safe() {
	defer func() {
		if r := recover(); r != nil {
			log.Println("recovered:", r)
		}
	}()
	mightPanic()
}

Use sparingly (HTTP server boundaries, plugin isolation). Business logic should return error.

Resource patterns
Context cancellation

For deadlines and cancellation, use context.Context — orthogonal to defer, but often paired in server code.