这panic recover code使用命名的返回值。
func main() {
result, err := foo()
fmt.Println("result:", result)
if err != nil {
fmt.Println("err:", err)
}
}
func foo() (result int, err error) {
defer func() {
if e := recover(); e != nil {
result = -1
err = errors.New(e.(string))
}
}()
bar()
result = 100
err = nil
return
}
func bar() {
panic("panic happened")
}
输出
result: -1
err: panic happened
但是为什么this code局部变量不起作用?
func main() {
result, err := foo()
fmt.Println("result:", result)
if err != nil {
fmt.Println("err:", err)
}
}
func foo() (int, error) {
var result int
var err error
defer func() {
if e := recover(); e != nil {
result = -1
err = errors.New(e.(string))
}
}()
bar()
result = 100
err = nil
return result, err
}
func bar() {
panic("panic happened")
}
输出
result: 0
有什么解释可以帮助我理解它的原因/基本概念吗? go tour basics中解释如下。
Named return values Go's return values may be named. If so, they are treated as variables defined at the top of the function.
所以应该是一样的吧?
最佳答案
请注意,这与 panic/recover 无关,它是 defer
的一个特性声明。
... if the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned. If the deferred function has any return values, they are discarded when the function completes.
关于go - 为什么 go panic recover to return value with local variable 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68554968/