Go:错误变量重新赋值,正确的使用方式是什么?

huangapple go评论106阅读模式
英文:

Go: error variable reassigning, proper use?

问题

我对Go语言中错误变量err的重新赋值感到困惑。

例如,我倾向于这样做:

err1 := Something()
checkErr(err1)
str, err2 := SomethingElse()
checkErr(err2)
err3 := SomethingAgain()
checkErr(err3)

但是我总是迷失其中,有成千上万个无用的err变量漂浮在代码中,而且这使得代码变得混乱和令人困惑。

但是如果我这样做:

err := Something()
checkErr(err)
str, err := SomethingElse()
checkErr(err)
err := SomethingAgain()
checkErr(err)

...它会报错说err已经被赋值。

但是如果我这样做:

var err error
err = Something()
checkErr(err)
str, err = SomethingElse()
checkErr(err)
err = SomethingAgain()
checkErr(err)

...它不起作用,因为str需要使用:=进行赋值。

我是不是漏掉了什么?

英文:

I'm confusing about the reassignment of the err variable for errors in Go.

For example, I tend to be doing this:

err1 := Something()
checkErr(err1)
str, err2 := SomethingElse()
checkErr(err2)
err3 := SomethingAgain()
checkErr(err3)

But I'm always losing track of this and have millions of useless err variables floating around that I don't need, and it makes the code messy and confusing.

But then if I do this:

err := Something()
checkErr(err)
str, err := SomethingElse()
checkErr(err)
err := SomethingAgain()
checkErr(err)

...it gets angry and says err is already assigned.

But if I do this:

var err error
err = Something()
checkErr(err)
str, err = SomethingElse()
checkErr(err)
err = SomethingAgain()
checkErr(err)

...it doesn't work because str needs to be assigned with :=

Am I missing something?

答案1

得分: 4

你快要完成了...在:=的左侧至少需要有一个新创建的变量。但是如果你没有提前声明err,编译器会尝试在每个:=的实例上创建它,这就是为什么你会得到第一个错误。所以这个例子可以工作,例如:

package main

import "fmt"

func foo() (string, error) {
 return "Bar", nil
}

func main() {
   var err error

   s1, err := foo()
   s2, err := foo()

   fmt.Println(s1, s2, err)
}

或者在你的情况下:

//我们先声明它
var err error

//这是一个普通的赋值
err = Something()
checkErr(err)

//在这里,编译器知道只有str是一个新声明的变量
str, err := SomethingElse()
checkErr(err)

//再次...
err = SomethingAgain()
checkErr(err)
英文:

you're almost there... at the left side of := there needs to be at least one newly create variable. But if you don't declare err in advance, the compiler tries to create it on each instance of :=, which is why you get the first error. so this would work, for example:

package main

import "fmt"

func foo() (string, error) {
 return "Bar", nil
}

func main() {
   var err error

   s1, err := foo()
   s2, err := foo()

   fmt.Println(s1,s2,err)
}

or in your case:

//we declare it first
var err error

//this is a normal assignment
err = Something()
checkErr(err)

// here, the compiler knows that only str is a newly declared variable  
str, err := SomethingElse()
checkErr(err)

// and again...
err = SomethingAgain()
checkErr(err)

huangapple
  • 本文由 发表于 2014年7月27日 22:10:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/24981794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定