当 struct
成员被分配返回值之一时,为什么我不能使用 :=
?
package main
import "fmt"
type Foo struct { Bar int64 }
func Baz() (int64, int64) { return 0, 0 }
func main() {
foo := Foo{}
var x int64
x, foo.Bar = Baz() // ok
y, foo.Bar := Baz() // error
fmt.Printf("%#v\n", foo)
}
编译错误为:
non-name foo.Bar on left side of :=
最佳答案
因为规范是这么说的。不,真的:
短变量声明只定义on identifier lists :
ShortVarDecl = IdentifierList ":="ExpressionList .
Identifiers lists不包括 Selectors :
IdentifierList = identifier { ","identifier } .
因此,在使用短变量声明语法时不允许分配选择器。
参见 this related issue了解详情。在那里你可以找到这种行为背后的原因:
The := notation is a shorthand for common cases. It's not meant to cover every possible declaration one may write. I'd prefer to leave as is, but won't close this until others have weighed in.
关于go - 使用速记分配/声明将返回值分配给结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23896030/