我是新来的,学习推迟。我想知道为什么第一个有效而第二个无效。我想知道它们之间有什么区别。
第一的:
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")
}
}
}
Second:
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")
}
}
}
The 规范说 https://golang.org/ref/spec#Handling_panics:
如果满足以下任一条件,recover 的返回值为 nil:
...
The 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")
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)