英文:
Assign return value to struct member with shorthand assignment/declaration
问题
为什么在给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() // 正常
y, foo.Bar := Baz() // 错误
fmt.Printf("%#v\n", foo)
}
编译错误信息为:
non-name foo.Bar on left side of :=
英文:
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\n", foo)
}
The compilation error is:
non-name foo.Bar on left side of :=
答案1
得分: 4
因为规范是这样规定的。不过,真的是这样的:
-
短变量声明只在标识符列表上定义:
ShortVarDecl = IdentifierList ":=" ExpressionList .
-
IdentifierList = identifier { "," identifier } .
因此,在使用短变量声明语法时,不允许分配选择器。
有关详细信息,请参阅此相关问题。在那里,您可以找到这种行为背后的原因:
> := 符号是常见情况的简写。它并不意味着涵盖每种可能的声明。我更愿意保持原样,但在其他人发表意见之前,我不会关闭此问题。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论