除了正常的函数结束使用外
对于下面的这一段代码
最终的输出结果为:
目前得到的解释为defer在调用函数之前就会提前求出函数中各个形参具体的值,所以对于
defer un(trace("a"))在执行到defer的时候就会执行函数un中的函数trace并得到返回值
看过的有一本书中写过defer能够影响到最终的返回值,差不多也是用到了同样的道理
package main
import "fmt"
func main() {
res := test()
fmt.Println("res:", res)
}
func test() (testRes int) {
testRes = 2
fmt.Println("in test testRes:", testRes)
defer func(i int) {
fmt.Println("defer func i:", i)
}(change(&testRes))
fmt.Println("level test testRes:", testRes)
return
}
func change(changeRes *int) int {
*changeRes++
return *changeRes
}
运行结果为: