如何在恐慌的 Go 函数中返回一个值? [英] How to return a value in a Go function that panics?

查看:25
本文介绍了如何在恐慌的 Go 函数中返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Go 函数应该返回一个值,但是在调用库函数时它可能会出现恐慌.我可以使用 recover() 在延迟调用中捕获它,但在这种情况下如何返回值?

My Go function is expected to return a value, but it may panic when calling a library function. I can use recover() to capture this in a deferred call, but how can I return a value in this case?

func MyFunc() string{
    defer func() {
        if err := recover(); err != nil {
            // What do I do to make MyFunc() return a value in case of panic?
        }
    }()
    SomeFuncThatMayPanic()
    return "Normal Return Value"
    // How can I return "ERROR" in case of panic?
}

推荐答案

可以使用命名结果参数.命名您的返回值,并在检测到恐慌时的延迟函数中,您可以更改返回变量"的值.将返回更改后的新值.

You can use named result parameters. Name your return values, and in the deferred function when panic was detected, you can change the values of the return "variables". The changed new values will be returned.

示例:

func main() {
    fmt.Println("Returned:", MyFunc())
}

func MyFunc() (ret string) {
    defer func() {
        if r := recover(); r != nil {
            ret = fmt.Sprintf("was panic, recovered value: %v", r)
        }
    }()
    panic("test")
    return "Normal Return Value"
}

输出(在 Go Playground 上试试):

Output (try it on the Go Playground):

Returned: was panic, recovered value: test

规范:延迟语句中提到了这一点:

This is mentioned in the Spec: Defer statements:

例如,如果延迟函数是 函数字面量,而周围的函数有 命名结果参数在字面量范围内,延迟函数可以访问和修改结果参数之前被退回.

For instance, 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.

博文中也提到了延迟、恐慌和恢复:

It is also mentioned in the blog post Defer, Panic and Recover:

延迟函数可以读取并分配给返回函数的命名返回值.

Deferred functions may read and assign to the returning function's named return values.

还有 Effective Go: Recover:

如果 doParse 发生恐慌,恢复块会将返回值设置为 nil——延迟函数可以修改命名的返回值.

If doParse panics, the recovery block will set the return value to nil—deferred functions can modify named return values.

这篇关于如何在恐慌的 Go 函数中返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆