我是 Go 的新手,我已经多次偶然发现以下问题。我不明白允许(或不允许)在 :=
的帮助下重新定义一个变量的基本规则是什么。
你能给我解释一下为什么 test := func3()
在第一个脚本中触发错误但在第二个脚本中运行正常吗?
两个脚本之间唯一不同的是调用 func3()
的行的位置。
谢谢!
第一个脚本
https://play.golang.org/p/vvCI7nxHZL
package main
import (
"fmt"
)
func func1() (string, string) {
return "", ""
}
func func2() (string, string) {
return "", ""
}
func func3() string {
return ""
}
func main() {
test, test2 := func1()
test, test3 := func2()
test := func3()
fmt.Println(test, test2, test3)
}
第二个脚本
https://play.golang.org/p/BTTYCGEJ4E
package main
import (
"fmt"
)
func func1() (string, string) {
return "", ""
}
func func2() (string, string) {
return "", ""
}
func func3() string {
return ""
}
func main() {
test := func3()
test, test2 := func1()
test, test3 := func2()
fmt.Println(test, test2, test3)
}
最佳答案
As described in Effective Go , :=
运算符,当左侧部分是名称列表时,声明尚未声明的名称。仅当已声明所有内容时才会引发错误。
这在这种典型情况下特别方便:
a, err := someCall()
if (err) ...
b, err := someOtherCall()
if (err) ...
在文档条款中:
In a := declaration a variable v may appear even if it has already been declared, provided:
- this declaration is in the same scope as the existing declaration of v (if v is already declared in an outer scope, the declaration will create a new variable §),
- the corresponding value in the initialization is assignable to v, and
- there is at least one other variable in the declaration that is being declared anew.
关于go - 为什么重新定义变量并不总是触发错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36938575/