no new variables on left side of :=

前端 未结 4 554
深忆病人
深忆病人 2020-12-13 08:18

What\'s happening here?

package main

import \"fmt\"

func main() {

    myArray  :=[...]int{12,14,26}  ;     
    fmt.Println(myArray)

    myArray  :=[...         


        
相关标签:
4条回答
  • 2020-12-13 08:52

    Remove the colon : from the second statement as you are assigning a new value to existing variable.

    myArray = [...]int{11,12,14}
    

    colon : is used when you perform the short declaration and assignment for the first time as you are doing in your first statement i.e. myArray :=[...]int{12,14,26}.

    0 讨论(0)
  • 2020-12-13 08:53
    myArray  :=[...]int{12,14,26}
    

    As stated by the previous commenters, := is a type of short-hand and/or the short-form of variable declaration.

    So in the statment above you are doing two things.

    1. You are declaring your variable to be myArray.
    2. You are assigning an array of integers to the myArray variable.

    The second part of your code fails, because what you are doing here:

    myArray  :=[...]int{11,12,14} //error pointing on this line 
    

    Is RE-declaring the existing variable myArray, which already contains integer values.

    This works:

    myArray = [...]int{11,12,14} // NO error will be produced by this line
    

    Because, it is assigning the integer array to the existing ( pre-declared / initialized ) variable.

    0 讨论(0)
  • 2020-12-13 09:06

    There are two types of assignment operators in go := and =. They are semantically equivalent (with respect to assignment) but the first one is also a "short variable declaration" ( http://golang.org/ref/spec#Short_variable_declarations ) which means that in the left we need to have at least a new variable declaration for it to be correct.

    You can change the second to a simple assignment statement := -> = or you can use a new variable if that's ok with your algorithm.

    0 讨论(0)
  • 2020-12-13 09:11

    As a side note, redeclaration can only appear in a multi-variable short declaration

    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.

    package main
    
    import "fmt"
    
    
    func main() {
        a, b := 1, 2
        c, b := 3, 4
    
        fmt.Println(a, b, c)
    }
    

    Here is a very good example about redeclaration of variables in golang: https://stackoverflow.com/a/27919847/4418897

    0 讨论(0)
提交回复
热议问题