英文:
Behavior of deferred functions in go
问题
我正在调用以下函数:
func main() {
defer func(t time.Time) {
log.Printf("took=%v", time.Since(t))
}(time.Now())
time.Sleep(5 * time.Second)
}
我注意到,正如预期的那样,延迟函数报告了实际的执行时间。
▶ go run main.go
2022/01/08 15:20:03 took=5.005078652s
我的问题是,实际上是通过什么机制实现的?
这行代码 defer func(t time.Time) 是否意味着在这个特定的点上,调用实际上已经完成(因此 t 取得了此时刻的时间值),这样它就可以估计实际的(main)函数调用了吗?
否则,如果延迟的匿名函数在 main 结束之前完全被调用,它怎么知道 main 实际上何时开始执行?
英文:
I am calling the following function
func main() {
defer func(t time.Time) {
log.Printf("took=%v", time.Since(t))
}(time.Now())
time.Sleep(5 * time.Second)
}
I noticed that as expected, the deferred function reports the actual entire time of execution.
▶ go run main.go
2022/01/08 15:20:03 took=5.005078652s
My question is what is the actual mechanism that allows this?
Does this line defer func(t time.Time) imply that at this specific point the invocation is actually done (therefore t takes the temporal value at this point in time) and that is the way it can estimate the actual (main) function invocation?
Otherwise, it the deferred anonymous function was entirely invoked just before main's exist, how would it know when main actually begun execution?
答案1
得分: 3
是的,这正是Go tour所说的:
延迟调用的参数会立即求值,但是函数调用会在包围函数返回之前才执行。
英文:
Yes, this is what even Go tour says:
> The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论