Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 147 ยท Functions

defer

Learn Go's defer statement - last-in-first-out order, when arguments are evaluated, cleanup of files and locks, defer in loops, changing named results, cost and panics.

Real programs acquire things: files, locks, network connections, temporary directories. Every one of them must be released, on every path out of the function, including early returns and errors. Forgetting one is a classic source of leaks. Go's answer is the defer statement: it schedules a function call to run when the surrounding function returns, no matter how it returns.

You write the cleanup right next to the code that needs it, so it is hard to forget and easy to review. This lesson covers the rules of defer precisely: the order deferred calls run in, when their arguments are evaluated, how to use it with resources, why it behaves surprisingly in loops, how it can change named results, what it costs, and how it cooperates with panics (previewed here and covered fully in panic and recover).

The basics

Put defer in front of any function or method call. The call does not happen now; it is remembered and executed just before the enclosing function returns:

Go Deferred calls run at the end

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.

The output order is start, middle, end of main, and only then deferred: cleanup. The deferred call waits until main is about to return.

Last in, first out

If you defer several calls, they run in reverse order, like a stack of plates. The most recently deferred call runs first:

Go Deferred calls form a stack

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.

You get loop finished, then deferred 3, deferred 2, deferred 1. Reverse order makes sense for cleanup: if you open A and then open B (which depends on A), you want to close B first and A second. Deferring right after each acquire gives you that ordering for free.

Arguments are evaluated immediately

This rule trips up many newcomers. The function value and its arguments are evaluated when the defer statement executes, not when the deferred call runs:

Go Arguments are captured at the defer statement

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.

The first deferred call prints 10, because x was copied at the moment of the defer. The second uses a closure that reads y when it eventually runs, so it prints 2. If you want the latest value, use a closure; if you want the value right now, pass it as an argument.

Cleaning up resources

The idiomatic use of defer is to release a resource immediately after acquiring it successfully. The sandbox lets programs create temporary files, so here is a realistic example:

Go Closing a file with defer

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.

Notice where defer f.Close() sits: directly after the error check for os.Create. If creation failed, there is nothing to close, so the defer must come after the check, not before. The same pattern protects a mutex (mu.Lock(); defer mu.Unlock(), see The sync Package), a database transaction or an HTTP response body.

For files you write to, Close can fail, and that error can mean data was lost. For serious code, check it explicitly, or use the named-result trick shown below. For read-only files, ignoring the Close error is common and fine.

defer in loops

A deferred call runs when the function returns, not when the loop iteration or block ends. Deferring inside a long loop therefore piles up calls and keeps every resource open until the function finishes:

Go Defer inside a loop waits for the function

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.

All three "opening" lines appear first, then all work done, then the three closes. If each iteration opened a file, you'd have them all open at once and could run out of file descriptors. The fix is to move the loop body into its own function so the defer runs at the end of each iteration:

Go One function per iteration

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.

Now each resource is closed before the next one is opened. An immediately invoked function literal (func() { ... }()) around the body works too.

Modifying named results

A deferred function runs after the return statement has stored its values into the result variables. If the results are named, the deferred closure can change them. This is how you add context to errors in one place:

Go Wrapping every error with defer

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.

The same technique reports a Close error from a file you wrote: defer func() { if cerr := f.Close(); err == nil { err = cerr } }(). It keeps the first error and only uses the close error if nothing else went wrong.

defer and panics

When a function panics, Go stops normal execution but still runs the deferred calls on the way out, from the panicking function up the call stack. That is how locks get released and files closed even when something goes badly wrong, and it is also where recover lives:

Go Deferred calls run during a panic (fails on purpose)

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.

Both deferred lines print (the second one first, by the LIFO rule), and then the runtime reports panic: runtime error: index out of range [3] with length 0, followed by goroutine 1 [running]: and a stack trace that mentions main.go:10, and the process exits with status 2. panic and recover shows how a deferred function can catch the panic with recover().

os.Exit and log.Fatal are different: they end the process immediately and do not run deferred calls.

Cost and when not to use it

Deferred calls used to be expensive; since Go 1.14 most are nearly free (the compiler inlines them as "open-coded defers" when the function has few of them and none in loops). Rule of thumb: use defer for correctness without worrying about speed. Only in a very hot inner loop is it worth measuring (Benchmarks and Fuzzing shows how to benchmark).

Remember that a deferred call's return values are discarded. defer f.Close() ignores the error Close returns; that is allowed, but go vet and linters may ask you to be explicit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What order do these deferred calls run in?

    defer fmt.Print("a"); defer fmt.Print("b"); defer fmt.Print("c")

    Deferred calls run last in, first out, so the call deferred last (c) runs first.
  2. 2. What does this print?

    n := 1; defer fmt.Println(n); n = 2

    Arguments to a deferred call are evaluated when the defer statement runs, so the printed value is the 1 that n held at that moment.
  3. 3. When does a defer inside a for loop body run?

    Defers belong to the function, not to blocks. Put the loop body in its own function if you need per-iteration cleanup.
  4. 4. Where should defer f.Close() be placed relative to the error check after os.Open?

    If Open failed, f is nil and there is nothing to close. Check the error first, then defer the cleanup.
  5. 5. Which of these does NOT run pending deferred calls?

    os.Exit terminates the process immediately. Returns, panics and runtime errors all run deferred calls while unwinding.

Summary

  • defer call() schedules a call to run when the enclosing function returns, on every path, including panics.
  • Deferred calls run in last-in, first-out order.
  • The function value and arguments are evaluated at the defer statement; a closure reads variables when it finally runs.
  • Defer cleanup right after a successful acquire: defer f.Close(), defer mu.Unlock().
  • Defers are tied to the function, so inside loops move the body into a helper function to release resources each iteration.
  • With named results, a deferred closure can read and change the returned values, which is handy for wrapping errors.
  • os.Exit and log.Fatal skip deferred calls; modern defer costs very little.

Next: Recursion shows functions that call themselves.