defer
Deferred calls are taken off a stack. They can still change a named result. An ordinary result is already copied.
defer postpones a call until the function returns. Several defer calls run in reverse order, like a stack: the last deferred call runs first.
func order() {
defer fmt.Print("1")
defer fmt.Print("2")
defer fmt.Print("3")
fmt.Print("0")
}
// печатает 0321
The arguments of defer are evaluated immediately, at the moment they are written, not at the moment of the call. defer release(n) remembers the n that exists now. If you need to see the value on the way out, defer a function with no argument and read the variable inside it.
A named result can still be changed by defer:
func inc() (n int) {
defer func() { n++ }()
return 1
}
// вернёт 2
return 1 writes 1 into the name n, then the deferred calls run, and only then does the function actually return n. If the result is not named, the copy has already been taken:
func wrong() int {
n := 1
defer func() { n++ }()
return n
}
// вернёт 1
Here defer increments the local n after the returned value has been copied. From the outside that is invisible.
Where defer belongs
Close a file, release a lock, stop a timer: acquiring the resource and the defer stand next to each other, so an early return forgets nothing. Do not defer heavy work "just so that it happens at the end": the reader should see that defer is cheap and guaranteed. And do not confuse it with finally from other languages inside a large body of two hundred lines. Extract a function, and the stack will be short again.
Practice
The order of defer
What does
orderfrom the lesson print: first the digit before the defer stack, then the deferred calls? Write the digits with no separator.A named result
What does the function return?
func inc() (n int) { defer func() { n++ }() return 1 }Write one number.
When arguments are evaluated
There is
n := 1and the linedefer fmt.Println(n), after whichn = 2runs and the function ends. What does the deferred call print?- 1
- 2
- 0
- Nothing, because n changed