您认为您可以重用err变量吗?

时间:2019-02-27 05:05:23

标签: go

例如,在这种情况下,err变量将立即完成其作用,因此我认为不必定义多个名称。

package main

func main() {
    foo, errFoo := foo()
    if errFoo != nil {
        panic(errFoo)
    }

    bar, errBar := bar()
    if errBar != nil {
        panic(errFoo)
    }
}

所以我将代码更改如下。

package main

func main() {
    foo, err := foo()
    if err != nil {
        panic(err)
    }

    bar, err := bar()
    if err != nil {
        panic(err)
    }
}

你们会遵循什么样的规则?

1 个答案:

答案 0 :(得分:3)

重用err变量非常普遍,尤其是使用short variable declaration格式。
通常,当您在任何时候遇到错误时,都可以处理并立即返回/恐慌。

因此,如果您有以下代码:

func foo() error{
   a, err := f1()
   if err != nil{
     return err
   }

   //... do something with a

  //if we are here we know err is nil, so we can reuse it easily without any information getting lost
  b, err := f2()
  if err != nil{
    return err
  }
   //... do something with b

  return nil
}

然后可以重用err