Can Panic Recovery Modify Local Variables in Function Literals in Go?

Susan Sarandon
Release: 2024-10-31 09:18:02
Original
327 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!