为什么在 Go 中有两种声明变量的方式,有什么区别和使用哪一种?

Why there are two ways of declaring variables in Go, what's the difference and which to use?

根据 Go 参考资料,有两种声明变量的方法

Variable_declarations(格式为var count = 0var count int

Short_variable_declarations(格式为count := 0

我发现很难决定使用哪一个。

我知道的区别(到现在)是:

但据我所知它们的行为是一样的。在参考中它也 says:

It (the count:=0way) is shorthand for a regular variable declaration with initializer expressions but no types

我的困惑是:

Variable declarations 明确声明了变量。 var 关键字是必需的,它很短并表达了所做的事情(在文件级别,除了注释之外的所有内容都必须以关键字开头,例如 packageimportconst, type, var, func)。与任何其他块一样,变量声明可以这样分组:

var (
    count int
    sum   float64
)

你不能用 Short variable declarations 做到这一点。您也可以在不指定初始值的情况下使用变量声明,在这种情况下,每个变量都将具有其类型的零值。 Short 变量声明不允许这样做,您必须指定初始值。

Go 的指导设计原则之一是使语法简洁。许多语句要求或允许声明仅在语句主体中可用的局部变量,例如 forifswitch 等。使语法更清晰更短的是,在这些情况下,简短的变量声明是合理的,并且它们所做的是明确的。

for idx, value := range array {
    // Do something with index and value
}

if num := runtime.NumCPU(); num > 1 {
    fmt.Println("Multicore CPU, cores:", num)
}

另一个区别:重新声明

引用语言规范:

Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.

这个也很方便。假设你想做正确的错误处理,你可以重用一个 err 变量,因为你很可能只需要它来检查上次函数调用期间是否有任何错误:

var name = "myfile.txt"

fi, err := os.Stat(name) // fi and err both first declared
if err != nil {
    log.Fatal(err)
}
fmt.Println(name, fi.Size(), "bytes")

data, err := ioutil.ReadFile(name) // data is new but err already exists
                                   // so just a new value is assigned to err
if err != nil {
    log.Fatal(err)
}

// Do something with data