go · level 2 · unit 4 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
The score changes after the defer. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
score := 1
defer fmt.Println("Final score:", score)
score = 10
fmt.Println("Score now:", score)
}
your turn
Your turn. Never leave the oven on.
Fill the first blank so the oven is always switched off, however bake ends. Then bake twice: once with 3 cakes or fewer, and once with more than 3.
output
press run to see what happens
fix it
Somebody left the zoo gate open. Fix it!
output
press run to see what happens
- The gate is never shut. Which line runs
returnbefore thedeferis even reached? - A
deferonly counts once Go has run that line. Put it straight after the gate opens. - Move the defer line up so it comes right after line 4, then run.
nailed it
you never forget to tidy up. :D
deferruns a call when the function ends, however it ends.- Several deferred calls run last first.
- Write the
deferstraight after the thing that needs tidying.
new words in your collection
- defer
- clean-up
This lesson isn’t saved. A free account remembers every lesson you finish.