×

go · level 2 · unit 4 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

saves a job for the moment the function ends.

Some jobs must happen at the end, whatever else goes on: switch off the lights, lock the doors, close the file. Write defer before a call and Go saves it, then runs it when the function ends.

It runs however the function ends: after the last line, after an early return because of an error, even during a panic. So write the right next to the thing that needs it, and you can never forget it.

Several deferred calls run last first, like a stack of plates: the last plate you put down is the first one you pick up.

package main
import "fmt"
func openShop(customers int) {
	fmt.Println("Lights on")
	defer fmt.Println("Doors locked")
	defer fmt.Println("Lights off")
	if customers == 0 {
		fmt.Println("Nobody came, closing early")
		return
	}
	fmt.Println("Serving", customers, "customers")
}
func main() {
	openShop(3)
	openShop(0)
}

Values in a deferred call are worked out when the defer line runs, not when the call finally happens.