gpt4 book ai didi

Golang 延迟关闭

转载 作者:行者123 更新时间:2023-12-01 19:43:42 25 4
gpt4 key购买 nike

我刚开始学习延迟。我想知道为什么第一个有效而第二个无效。我想知道他们之间有什么区别。第一:

func say(s string) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in cleanup:", r)
}
wg.Done()
}()
for i := 0; i < 3; i++ {
fmt.Println(s)
time.Sleep(time.Millisecond * 100)
if i == 2 {
panic("oh")
}
}
}

第二个:

func cleanup(){
if r := recover(); r != nil {
fmt.Println("Recovered in cleanup:", r)
}
}

func say(s string) {
defer func() {
cleanup()
wg.Done()
}()
for i := 0; i < 3; i++ {
fmt.Println(s)
time.Sleep(time.Millisecond * 100)
if i == 2 {
panic("oh")
}
}
}

最佳答案

specification says :

The return value of recover is nil if any of the following conditions holds:

...

  • recover was not called directly by a deferred function.

cleanup() 函数由匿名延迟函数调用。重写代码以直接延迟 cleanup()

func say(s string) {
defer wg.Done()
defer cleanup() // cleanup called directly by defer
for i := 0; i < 3; i++ {
fmt.Println(s)
time.Sleep(time.Millisecond * 100)
if i == 2 {
panic("oh")
}
}
}

关于Golang 延迟关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62506585/

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