Can Panic Recovery Modify Local Variables in Function Literals?
In Go, when working with named return values, you can use a defer statement to modify the values before returning them. However, this behavior is not consistent when using local variables in function literals.
Consider the following code:
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")
}
This code works as expected, setting result to -1 and err to a custom error message after recovering from a panic. However, if we use local variables within the function literal, the behavior changes:
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")
}
In this case, result is reset to 0 instead of -1. This is because the defer statement in the function literal cannot access or modify the named return values since they are no longer in scope.
As per the Go documentation, "... 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."
Therefore, it is crucial to use named return values when trying to modify them using a defer statement within a function literal. Local variables in such cases cannot be accessed or modified.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3