dso0139 2016-04-20 18:51
浏览 27
已采纳

如果没有错误,则返回Golang

In Golang, is it ok to run the function

err, value := function()
if err == nil {
  return value
}

instead of doing this:

err, value := function()
if err != nil {
  panic(err)
}
return err

If so, is there any time advantages / bonuses?

This is not a non-fatal error. I am trying to convert something to different types, and i'm not sure which I should use.

  • 写回答

1条回答 默认 最新

  • duan0417 2016-04-20 19:01
    关注

    A panic is similar to an exception, but doesn't get passed to the caller (aka when you call panic, it happens then and there; you don't get to wait). You should go with the first sample of your code, where you can attempt an action, fail, and continue.

    func main() {
        s1 := rand.NewSource(time.Now().UnixNano())
        r1 := rand.New(s1)
    
        // Generate some random numbers, and call into add()
        for i := 0; i < 10; i++ {
            s, err := add(r1.Intn(100), r1.Intn(100))
            if err != nil {
                fmt.Println(err)
                continue
            }
            fmt.Println(s)
        }
    }
    
    // Error if we get a sum over 100
    func add(a int, b int) (int, error) {
        s := a + b
        if s > 100 {
            return s, errors.New("Hey doofus, error!")
        }
        return s, nil
    }
    

    If you were to panic in this example, you'd be done (try it-- instead of returning an error do panic("Some error"). But instead, we determine there's an error, and we can try to generate another random number.

    Like others have said, if you have a use case where you just can't recover (say you were trying to read from a file, but the file isn't there), you might decide it's better to panic. But if you have a long running process (like an API), you'll want to keep churning, despite any errors.

    GoPlay here: http://play.golang.org/p/ThXTxVfM6R

    OP has update his post with a use case-- he's trying to convert to a type. If you were to panic in this function, you would be dead in the water. Instead, we want to return an error, and let the caller decide what to do with the error. Take this as an example:

    func interfaceToString(i interface{}) (string, error) {
        if i == nil {
            return "", errors.New("nil interface")
        }
    
        switch i.(type) {
        case string:
            return i.(string), nil
        case float64:
            return strconv.Itoa(int(i.(float64))), nil
        case int:
            return strconv.Itoa(i.(int)), nil
        }
    
        return "", errors.New(fmt.Sprintf("Unable to convert %v", i))
    }
    

    GoPlay here: http://play.golang.org/p/7y7v151EH4

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化