July 21, 2020

Golang short variable declaration gotcha

Golang allows short variable declaration in the form of i:=0, which defines a integer variable i. Golang also allows multi-variable short declaration, e.g.

i,j := 0,1

In this case, as long as there is one new variable on the left side, for example, i, the compiler would be happy. However, if j is not defined in the SAME BLOCK SCOPE, a new j will be created! Most times this is not what you want. Got to be very careful with that. A full example:

func test(){
    j:=1;
    if j==1 {
        i,j:=2,3
    }
    fmt.Println(j) // j is still 1!!
}

No comments:

Post a Comment