dt2015 2016-04-29 12:38
浏览 32
已采纳

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

I'm quite new to Go and I've stumble upon the following problem a few times already. I don't understand what's the underlying rule that allows (or not) the redefining of one variable with the help of :=.

Can you please explain to me why test := func3() does trigger an error in the first script but works fine in the second script?

The only thing that changes between both scripts is the position of the line that calls func3().

Thanks!

1st script

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)
}

2nd script

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)
}
  • 写回答

1条回答 默认 最新

  • dongmie3526 2016-04-29 12:40
    关注

    As described in Effective Go, the := operator, when the left part is a list of names, declares the ones which aren't already declared. An error is only raised when all are already declared.

    This is especially convenient in this typical case:

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

    In the documentation terms:

    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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义