A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.
The expression must be a function or method call; it cannot be parenthesized. Calls of built-in functions are restricted as for expression statements.
Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked. Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred. That is, if the surrounding function returns through an explicit return statement, deferred functions are executed after any result parameters are set by that return statement but before the function returns to its caller. If a deferred function value evaluates to
nil
, execution panics when the function is invoked, not when the "defer" statement is executed.For instance, if the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned. If the deferred function has any return values, they are discarded when the function completes. (See also the section on handling panics.)
调用时机分别是
- 函数结束
- 函数中执行了return
- goroutine发生panic
package main
import (
"fmt"
)
func trace(s string) string {
fmt.Println("entering:", s)
return s
}
func un(s string) {
fmt.Println("leaving:", s)
}
func a() {
defer un(trace("a"))
fmt.Println("in a")
}
func b() {
defer un(trace("b"))
fmt.Println("in b")
a()
fmt.Println("c", c())
}
func c() (result int) {
defer func() {
// result is accessed after it was set to 6 by the return statement
result *= 7
}()
return 6
}
func main() {
b()
}
// entering: b
// in b
// entering: a
// in a
// leaving: a
// c 42
// leaving: b
执行的时候所有的参数都已经计算完了,相当于执行了两句语句
trace("b")
defer un("b")
多个defer采用的是FILO
由于defer在return结束之后调用,c函数中result先被赋值6,再执行defer,结果是42