Search code examples
variablesgovariable-declaration

Providing types explicitly in Go var declaraction fails while implicit works


I am new to go and currently going through the go tool tour.

While on the Short variable declarations section, I modified the sample code to look like this?

package main

import "fmt"

func main() {
    var i, j int = 1, 2
    k := 3
    var c bool, python string = true, "test"

    fmt.Println(i, j, k, c, python)
}

However, then I run the above code, I get the error:

# command-line-arguments
./compile233.go:8:12: syntax error: unexpected comma at end of statement

However, if I remove the types from the var declaration like the following:

package main

import "fmt"

func main() {
    var i, j int = 1, 2
    k := 3
    var c, python = true, "test"

    fmt.Println(i, j, k, c, python)
}

It works.

I cannot figure out what is wrong with the first example, and the error seems a bit misleading to me. Could anyone explain what I did wrong and why I'm getting the error?


Solution

  • The variable declaration statement is defined as

    VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
    VarSpec     = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
    

    which means that if you want to declare multiple variables with type specified explicitly in a single statement they all must have the same type. And that type must come after the identifier list.

    So

    var foo, bar bool // is valid
    var foo bool, bar bool // is not (only one type qualifier is allowed)
    

    Reference: