gpt4 book ai didi

go - 为什么当 annoymouse 函数返回时 defer 语句的工作方式不同

转载 作者:行者123 更新时间:2023-12-01 22:16:59 26 4
gpt4 key购买 nike

在这里我声明了一个延迟 trace1 的函数

func TestDeferFunc(t *testing.T) {
fmt.Println("start", time.Now())
defer trace1()
time.Sleep(3 * time.Second)
}

func trace1() {
startTime := time.Now()
fmt.Println("end time: ", startTime)
fmt.Println("execute time: ", time.Since(startTime))
}

运行后 go test -run=^TestDeferFunc$ ,下面是我得到的
start 2019-11-26 12:50:59.59489797 +0800 CST m=+0.000202866
end time: 2019-11-26 12:51:02.595090951 +0800 CST m=+3.000395880
execute time: 49.065µs

但是,当我推迟另一个恼人的功能时,事情发生了变化

func TestDeferFunc(t *testing.T) {
fmt.Println("start", time.Now())
defer trace2()()
time.Sleep(3 * time.Second)
}

func trace2() func() {
startTime := time.Now()
fmt.Println("end time: ", startTime)
fmt.Println("execute time: ", time.Since(startTime))
return func() {
fmt.Println("zzz")
}
}

下面是 go test结果
start 2019-11-26 12:52:58.318472958 +0800 CST m=+0.000197852
end time: 2019-11-26 12:52:58.318554368 +0800 CST m=+0.000279262
execute time: 4.853µs
zzz

有人可以帮帮我吗!谢谢

最佳答案

这是因为 defer仅声明 defer s 评估的函数调用 - 函数调用在时间 defer 进行评估执行。根据文档:

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.



您的代码 defer trace2()()基本上等于 f := trace2(); defer f() .所以 trace2立即被评估(并因此被调用)。

因此,要实现您可能想要的(跟踪时间),您可以使用 defer trace3()()trace3()像这样:
func trace3() func() {
startTime := time.Now()

return func() {
fmt.Println("end time: ", time.Now())
fmt.Println("execute time: ", time.Since(startTime))
}
}

关于go - 为什么当 annoymouse 函数返回时 defer 语句的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59043992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com