Golang mixed assignment and declaration

后端 未结 4 1827
一个人的身影
一个人的身影 2020-12-03 10:07

I started working with go for a few weeks, and (once again) I stumbled across something that seems odd for me:

// Not working
a := 1
{
    a, b := 2, 3
}

//         


        
4条回答
  •  盖世英雄少女心
    2020-12-03 11:03

    According to the golang the documentation:

    An identifier declared in a block may be redeclared in an inner block.

    That's exactly what your example is showing, a is redeclared within the brackets, because of the ':=', and is never used.

    A solution is to declare both variable and then use it:

    var a, b int
    {
        b, a = 2, 3
        fmt.Println(b)
    }
    fmt.Println(a)
    

提交回复
热议问题