将返回值分配给结构成员时使用简写赋值/声明

huangapple go评论87阅读模式
英文:

Assign return value to struct member with shorthand assignment/declaration

问题

为什么在给struct成员赋值时不能使用:=

playground

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?

playground

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

因为规范是这样规定的。不过,真的是这样的:

因此,在使用短变量声明语法时,不允许分配选择器。

有关详细信息,请参阅此相关问题。在那里,您可以找到这种行为背后的原因:

> := 符号是常见情况的简写。它并不意味着涵盖每种可能的声明。我更愿意保持原样,但在其他人发表意见之前,我不会关闭此问题。

英文:

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.

huangapple
  • 本文由 发表于 2014年5月28日 02:01:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/23896030.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定