Skip to content

Defer

Intermediate · Functions & Errors

defer schedules a call to run when the surrounding function returns. Deferred calls run in LIFO order and execute on every return path — the idiomatic way to guarantee cleanup (defer f.Close()).

  • defer1 — LIFO order (and shaping a named return value)
  • defer2 — guaranteed cleanup on every return path

Deferred calls run when the surrounding function returns, in LIFO order

Show hint
Defers run LIFO. With a named return seq, deferred appends mutate it:
defer func() { seq = append(seq, 1) }()
defer func() { seq = append(seq, 2) }()
defer func() { seq = append(seq, 3) }() // runs first -> [3,2,1]

Source

defer is the idiomatic way to guarantee cleanup runs on every return path

Show hint
Defer the cleanup at the top so it runs on every return:
defer r.Close()

Source