no new variables on left side of :=

前端 未结 4 562
深忆病人
深忆病人 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 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

提交回复
热议问题