英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论