Why Does Panic Recovery with Local Variables Not Work in Go?
In Go, it's common practice to use panic and recovery for error handling. However, there's a subtle difference in behavior when using local variables for return values in panic recovery.
Consider the following code:
<code class="go">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") }</code>
When panic occurs in bar(), the recover() function in the deferred closure is executed. It assigns -1 to result and creates an error object. The output of this code is correct:
result: -1 err: panic happened
However, if we use local variables for the return values:
<code class="go">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") }</code>
In this case, the output is different:
result: 0
This is because the recover() function assigns -1 to the local variable 'result'. However, since the function returns the named return value result (which was zero-initialized), the local variable assignment has no effect.
The reason for this behavior lies in the Go tour basics:
"Named return values...are treated as variables defined at the top of the function."
When using named return values, changes to them inside the defer closure are reflected in the returned values. However, when using local variables, the changes are only reflected in the local scope, not in the returned values.
The above is the detailed content of Why Does Panic Recovery with Local Variables Not Change the Returned Values in Go?. For more information, please follow other related articles on the PHP Chinese website!