Why can't I use :=
when a struct
member is being assigned one of the return values?
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
", foo)
}
The compilation error is:
non-name foo.Bar on left side of :=
Because the spec says so. No, really:
Short variable declarations are only defined on identifier lists:
ShortVarDecl = IdentifierList ":=" ExpressionList .
Identifiers lists do not include Selectors:
IdentifierList = identifier { "," identifier } .
Therefore, you are not allowed to assign a selector when using the short variable declaration syntax.
See this related issue for details. There you can find the reasoning behind this behaviour:
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.