Multiple variables of different types in one line in Go (without short variable declaration syntax)

It's possible if you omit the type:

var i, s = 2, "hi"
fmt.Println(i, s)

Output (try it on the Go Playground):

2 hi

Note that the short variable declaration is exactly a shorthand for this:

A short variable declaration uses the syntax:

ShortVarDecl = IdentifierList ":=" ExpressionList .

It is shorthand for a regular variable declaration with initializer expressions but no types:

"var" IdentifierList = ExpressionList .

Without omitting the type it's not possible, because the syntax of the variable declaration is:

VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .

(There is only one optional type for an identifier list with an expression list.)

Also I assume you don't count this as 1 line (which otherwise is valid syntax, but gofmt breaks it into multiple lines):

var (i int = 2; s string = "hi")

Also if you only want to be able to explicitly state the types, you may provide them on the right side:

var i, s = int(2), string("hi")

But all in all, just use 2 lines for 2 different types, nothing to lose, readability to win.


This isn't exactly specific to the OP's question, but since it gets to appear in search results for declaring multiple vars in a single line (which isn't possible at the moment). A cleaner way for that is:

var (
    n []int
    m string
    v reflect.Value
)

Tags:

Go