Defer
The keyword defer puts a function call aside. The call runs later, when the function around it returns:
package main
import "fmt"
func process() {
defer fmt.Println("closed")
fmt.Println("working")
}
func main() {
process()
fmt.Println("back in main")
}
Output:
working
closed
back in main
The deferred line comes first in the code, but it runs last. Go saves the call when it reaches the defer line. Then, just before process returns to main, it runs the saved call.
Why use defer?
Real programs often open something that must be closed again, like a file or a network connection. With defer, you write the close right below the open, so you cannot forget it. The deferred call runs on every way out of the function, also on an early return:
package main
import "fmt"
func check(n int) {
defer fmt.Println("done checking", n)
if n < 0 {
fmt.Println("negative")
return
}
fmt.Println("ok")
}
func main() {
check(-1)
check(5)
}
Output:
negative
done checking -1
ok
done checking 5
For -1, the function returns early, and the deferred line still runs. For 5, it runs at the normal end.
Several defers: last in, first out
When a function defers more than one call, they run in reverse order. The last one deferred runs first, like a stack of plates where you take the top plate first. Here the defers are in main, so they run when main ends:
defer fmt.Println("first")
defer fmt.Println("second")
defer fmt.Println("third")
fmt.Println("start")
Output:
start
third
second
first
This also happens with a defer inside a loop. Each one waits for the end of the function, not the end of the loop:
for i := 1; i <= 3; i++ {
defer fmt.Println("defer", i)
}
fmt.Println("loop done")
Output:
loop done
defer 3
defer 2
defer 1
Arguments are evaluated right away
Only the call waits. Go works out the arguments at the moment it reaches the defer line:
x := 1
defer fmt.Println("deferred x:", x)
x = 2
fmt.Println("x now:", x)
Output:
x now: 2
deferred x: 1
When the defer line ran, x was 1, so Go saved 1. Changing x later does not change the saved value.
If you want the value at the end of the function, defer a closure. A closure uses the variable itself, not a saved copy:
y := 1
defer func() {
fmt.Println("closure sees y:", y)
}()
y = 2
Output:
closure sees y: 2
The Panic and Recover lesson shows one more important use of defer.
In the exercise, add defer in two places so Working prints before the steps, the steps print from the last one back to the first, and Closing prints at the very end.