Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Keywords and Statements

The defer statement

Reference for Go defer: schedule a call to run when the function returns, last-in-first-out order, argument evaluation time, loops, named results and panics.

defer schedules a function or method call to run just before the surrounding function returns, whether it returns normally, through a return statement, or because of a panic. It is the standard way to pair an acquire with its release: close a file, unlock a mutex, finish a trace span.

Deferred calls run in last-in-first-out order. The function value and the arguments are evaluated immediately, when the defer statement executes, but the call itself happens later.

Go
f, err := os.Open(name)
if err != nil {
    return err
}
defer f.Close()

Try it

Go Order and argument evaluation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Named results, closures and recover

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
DeferStmt = "defer" Expression .

The expression must be a function or method call (it may be a call of a function literal). Calls of some built-in functions are not permitted as statements, so defer append(...) or defer len(x) are errors; defer close(ch), defer delete(m, k), defer panic(...), defer print(...) and defer recover() are allowed.

Part Description
Function value Evaluated when the defer statement runs. If it is nil, the panic happens when the deferred call executes, not at the defer.
Arguments Evaluated immediately and saved. Later changes to the variables do not affect them (unless you pass pointers or use a closure).
Results Discarded.

Usage notes

  • Order. Deferred calls run last-in, first-out, so resources are released in reverse order of acquisition.
  • Arguments are captured early. defer fmt.Println(x) prints the value x had at the defer. To see the final value, use a closure: defer func() { fmt.Println(x) }().
  • Named results. A deferred closure can read and modify named result parameters after a return statement has set them. This is how wrappers add context to errors.
  • Loops. Deferred calls run when the function ends, not at the end of each iteration. Deferring f.Close() inside a loop that opens many files keeps them all open. Move the body into a helper function or close explicitly.
  • Panics. Deferred functions still run during a panic. A call to recover() directly inside a deferred function stops the panic and returns the panic value. See recover() and panic().
  • Check the error from Close for writes. defer f.Close() ignores the error; for files you wrote, capture it through a named result.
  • Cost. Defer is cheap in modern Go (open-coded in most functions), so do not avoid it for performance except in the hottest paths.
  • os.Exit. Deferred calls do not run when the program ends via os.Exit or log.Fatal.
  • Methods. defer mu.Unlock() evaluates the receiver mu at the defer; for value receivers a copy is made then.