Home >Backend Development >Golang >Can Panic Recovery Modify Local Variables in Function Literals in Go?
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:
<code class="go">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") }</code>
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:
<code class="go">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") }</code>
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.
The above is the detailed content of Can Panic Recovery Modify Local Variables in Function Literals in Go?. For more information, please follow other related articles on the PHP Chinese website!