defer, precisely in Go
Deferred calls run last-in-first-out, with arguments evaluated immediately.
func order() []string {
var log []string
record := func(s string) { log = append(log, s) }
value := "first"
defer record("deferred with " + value) // captured now
defer func() { record("closure sees " + value) }()
value = "second"
record("body")
return log // note: defers run after this is evaluated
}
func cleanup() (steps []string) {
defer func() { steps = append(steps, "outer") }()
defer func() { steps = append(steps, "inner") }()
return []string{"body"}
}
How it works
- The argument is captured at the defer statement, not at the call.
- A closure sees the variable's final value instead.
- Defers run on every path out, including a panic.
Keywords and builtins used here
appenddeferfuncreturnstringvar
The run, in numbers
- Lines
- 18
- Characters to type
- 465
- Tokens
- 117
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 67 seconds.
Step 2 of 4 in defer, panic & recover, step 11 of 15 in Errors.