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

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

问题描述

根据Go引用,有两种方法可以声明变量:

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



Short_variable_declarations (in格式为 count:= 0



我发现决定使用哪一个非常混乱。 p>

我知道的差异(直到现在)是:


  • 我只能使用在函数的作用域中 count:= 0 格式。

  • count:= 0 可以在多变量短期申报中被重新申报
  • 但是,据我所知,他们的表现完全相同 。在参考文献中还表示



    对于具有初始化表达式的常规变量声明,它( count:= 0 方式)是速记,但

    没有类型


    我的疑惑是:


    • 如果一方只是另一方的速记方式,他们为什么表现不同?

    • Go的作者在做什么关注时提出了两种声明变量的方法(为什么他们没有合并成一种方式)?只是为了让我们感到迷惑?

    • 在使用它们的时候,我还有什么其他方面需要关注,以防我陷入坑中?


    解决方案

    变量声明明确说明变量是被声明的。 var 关键字是必需的,它是简短的并且表示所做的事情(在文件级别,除注释以外的所有内容都必须以关键字开头,例如 package 导入 const 类型 var func )。像任何其他块一样,变量声明可以像这样分组:

      var(
    count int
    sum float64

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



    Go的指导性设计原则之一是使语法清晰。许多语句要求或者它们允许声明局部变量,这些变量仅在语句的主体中可用,如, if code>, switch 等。为了使语法更清晰和更短,在这些情况下Short变量声明是合理的,并且它们的功能是不明确的。

     对于idx,value:= range array {
    //做一些索引和值
    }

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

    另一个区别:Redeclaration

    引用语言规范:


    与常规变量声明不同,短变量声明可能会重新声明变量,前提是它们最初是在相同类型的同一个块中声明的,并且至少有一个非空变量是新变量。因此,重新宣布只能出现在多变量的短期声明中。重新申报不会引入新的变数;它只是分配一个新的价值原。


    这一个也很方便。假设你想做适当的错误处理,你可以重用一个 err 变量,因为很可能你只需要在最后的函数调用过程中检查是否有错误:

      var name =myfile.txt

    fi,err:= os.Stat(name)/ / fi和err首先声明
    ,如果err!= nil {
    log.Fatal(err)
    }
    fmt.Println(name,fi.Size(),bytes )

    data,err:= ioutil.ReadFile(name)//数据是新的,但err已经存在
    //所以只是一个新值被赋值给err
    if err!= nil {
    log.Fatal(err)
    }

    //用数据做一些事


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

    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:

    • 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:

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

    My confusions are:

    • If one is just the shorthand way of the other, why do they behave differently?
    • In what concern does the author of Go make two ways of declaring a variable (why are they not merged into one way)? Just to confuse us?
    • Is there any other aspect that I should keep my eyes open on when using them, in case I fall into a pit?

    解决方案

    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
    )
    

    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.

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

    Another difference: Redeclaration

    Quoting from the Language specification:

    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.

    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天全站免登陆