doushi4864 2019-02-07 16:24 采纳率: 100%
浏览 70
已采纳

在Go中返回错误时结果值的最佳做法

If your function returns both a value type and also an error type, is it "the go way" to make sure the value type is niled/zero-valued when the error type is non-nil?

Example:

func mayError() ([]string, error) {
  ...
}

Should the []string return value be nil if the error is not nil?

  • 写回答

1条回答 默认 最新

  • duanhongyi2964 2019-02-07 16:45
    关注

    Generally speaking, if a function failed to complete a task, its return value should be treated as unreliable. Because errors in go are values, the caller may ignore the error it returns. For exmaple:

    foo := myType{
        Bar: 123,
        Foo: "some string",
    }
    
    b, _ := json.Marshal(foo)
    

    I'm ignoring the error because it's a type I've created, and I know it can be marshalled. However, it's considered bad practice either way. All the same, now imagine someone calling your function:

    slice, _ := mayError()
    

    And your function, after adding 2 elements to the slice, errors. Returning the partial slice could, and probably will, lead to buggy behaviour further down the line. That makes code hard to debug. On balance, I'd say it's best to return a nil slice and an error in that case. If the code looks like this:

    slice, _ := mayError() // returns nil, someErr
    // panic
    if slice[0] != "" {
    }
    

    At least the error shows up immediately, and you'll see any errors returned by mayError are being ignored. This makes the code way easier to debug/maintain/fix.

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

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集