为什么在 Go 中有两种声明变量的方式,有什么区别以及使用哪种方式? [英] Why there are two ways of declaring variables in Go, what's the difference and which to use?

查看:20
本文介绍了为什么在 Go 中有两种声明变量的方式,有什么区别以及使用哪种方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Go 引用,有两种声明变量的方式

According to the Go reference there are two ways of declaring a variable

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

Short_variable_declarations(格式为count := 0)

Variable_declarations (in the format of var count = 0 or var count int)
and
Short_variable_declarations (in the format of count := 0)

我发现决定使用哪个非常令人困惑.

I found it's very confusing to decide which one to use.

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

The differences I know (till now) are that:

  • 我只能在函数范围内使用 count := 0 格式.
  • count := 0 可以在多变量短声明重新声明.
  • I can only using a count := 0 format when in the scope of a function.
  • count := 0 can be redeclared in a multi-variable short declaration.

但据我所知,他们的行为确实相同.在参考文献中它也:

But they do behave the same as far as I know. And in the reference it also says:

它(count:=0方式)是带有初始化表达式但没有类型的正则变量声明的简写

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

我的困惑是:

  • 如果一个只是另一个的简写方式,为什么它们的行为会不同?
  • Go 的作者在什么方面考虑了两种声明变量的方式(为什么它们不合并为一种方式)?只是为了迷惑我们?
  • 在使用它们的时候还有什么需要注意的地方吗,以防我掉进坑里?

推荐答案

变量声明使很明显,声明了变量.var 关键字是必需的,它很短,表示做了什么(在文件级别,除了注释之外的所有内容都必须以关键字开头,例如 package, importconsttypevarfunc).像任何其他块一样,变量声明可以这样分组:

The Variable declarations make it clear that variables are declared. The var keyword is required, it is short and expresses what is done (at the file level everything excluding comments has to start with a keyword, e.g. package, import, const, type, var, func). Like any other block, variable declarations can be grouped like this:

var (
    count int
    sum   float64
)

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

You can't do that with Short variable declarations. Also you can use Variable declarations without specifying the initial value in which case each variable will have the zero value of its type. The Short variable declaration does not allow this, you have to specify the initial value.

Go 的指导设计原则之一是使语法清晰.许多语句需要或方便地允许声明局部变量,这些变量仅在语句主体中可用,例如 forifswitch 等.为了使语法更简洁、更简洁,Short 变量声明在这些情况下是合理的,并且它们的作用是明确的.

One of Go's guiding design principle was to make the syntax clean. Many statements require or it is handy that they allow declaring local variables which will be only available in the body of the statement such as for, if, switch etc. To make the syntax cleaner and shorter, Short variable declaration is justified in these cases and it is unambigous what they do.

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 变量,因为很可能您只需要它来检查上次函数调用期间是否有任何错误:

This one is also handy. Suppose you want to do proper error handling, you can reuse an err variable because most likely you only need it to check if there were any errors during the last function call:

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

这篇关于为什么在 Go 中有两种声明变量的方式,有什么区别以及使用哪种方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆