相关疑难解决方法(0)

如何在一个恐慌的Go函数中返回一个值?

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

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?
}
Run Code Online (Sandbox Code Playgroud)

exception-handling recover go

9
推荐指数
1
解决办法
2723
查看次数

函数返回后是否延迟运行?

我一直盯着这段代码,但无法弄清楚其行为的原因。

package main

import (
    "fmt"
)

var i int

func example() int {
    defer func() {
        fmt.Println("defer")
        i = 1
    }()

    fmt.Println("first")
    return i
}

func main() {
    fmt.Println(example())
    fmt.Println(i)
}
Run Code Online (Sandbox Code Playgroud)

首先,我的预期输出是:

first
defer
1
1
Run Code Online (Sandbox Code Playgroud)

但是,正如您在操场上看到的,实际输出是:

first
defer
0
1
Run Code Online (Sandbox Code Playgroud)

这是延迟匿名函数行为吗?没有

那么,为什么要打印呢0

go

2
推荐指数
1
解决办法
638
查看次数

标签 统计

go ×2

exception-handling ×1

recover ×1