go - 使用速记分配/声明将返回值分配给结构成员

标签 go

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() // ok

  y, foo.Bar := Baz() // error

  fmt.Printf("%#v\n", foo)
}

编译错误为:

non-name foo.Bar on left side of :=

最佳答案

因为规范是这么说的。不,真的:

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

参见 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/

相关文章:

go - 将结构布局为字节

go - Gos是否有MarshalURLQuery的实现?

go - 当我导航到其他页面时发送 WebSocket 错误关闭

git - 如何使 git2go tree.Walk() 非递归并显示文件夹并从目标文件夹开始?

html - Golang、GAE、重定向用户?

go - 自定义阅读器直到遇到标记

go - 使用Go从Firestore获取单个文档的惯用方式是什么?

go - *文件类型如何作为阅读器类型传递?

go - 具有 WaitGroup 和无缓冲 channel 的竞争条件

go - go if/for/func block open brace position 需要在同一行吗?