go - 为什么重新定义变量并不总是触发错误?

标签 go

我是 Go 的新手,我已经多次偶然发现以下问题。我不明白允许(或不允许)在 := 的帮助下重新定义一个变量的基本规则是什么。

你能给我解释一下为什么 test := func3() 在第一个脚本中触发错误但在第二个脚本中运行正常吗?

两个脚本之间唯一不同的是调用 func3() 的行的位置。

谢谢!

第一个脚本

https://play.golang.org/p/vvCI7nxHZL

package main

import (
  "fmt"
)

func func1() (string, string) {
  return "", ""
}

func func2() (string, string) {
  return "", ""
}

func func3() string {
  return ""
}

func main() {
  test, test2 := func1()
  test, test3 := func2()
  test := func3()

  fmt.Println(test, test2, test3)
}

第二个脚本

https://play.golang.org/p/BTTYCGEJ4E

package main

import (
  "fmt"
)

func func1() (string, string) {
  return "", ""
}

func func2() (string, string) {
  return "", ""
}

func func3() string {
  return ""
}

func main() {
  test := func3()
  test, test2 := func1()
  test, test3 := func2()

  fmt.Println(test, test2, test3)
}

最佳答案

As described in Effective Go , := 运算符,当左侧部分是名称列表时,声明尚未声明的名称。仅当已声明所有内容时才会引发错误。

这在这种典型情况下特别方便:

a, err := someCall()
if (err) ...
b, err := someOtherCall()
if (err) ...

在文档条款中:

In a := declaration a variable v may appear even if it has already been declared, provided:

  • this declaration is in the same scope as the existing declaration of v (if v is already declared in an outer scope, the declaration will create a new variable §),
  • the corresponding value in the initialization is assignable to v, and
  • there is at least one other variable in the declaration that is being declared anew.

关于go - 为什么重新定义变量并不总是触发错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36938575/

相关文章:

arrays - 或突然减速取决于阵列大小

Go需要逗号,放在那里会抛出其他不相关的错误

go - 使用具有 OOP 风格的 fyne 小部件

gopls 禁用结构自动填充

Golang OpenGL元素缓冲对象无法正确渲染

go - 在 Go 中,类型名称大写是惯例吗?

mongodb - 无法从 MongoDB 中解码 ObjectId SubValue 结果在 Golang 中

go - json编码(marshal)数据的proto3消息类型

html - 使用Golang的HTML模板中的发件人姓名邮件

go - 如何从 Go 中的字符串中替换最后两个 '/' 字符