I was wondering if there's a way with Go to declare and initialise multiple variables of different types in one line without using the short declaration syntax :=
.
Declaring for example two variables of the same type is possible:
var a, b string = "hello", "world"
Declaring variables of different types with the :=
syntax is also possible:
c, d, e := 1, 2, "whatever"
This gives me an error instead:
var f int, g string = 1, "test"
Of course I'd like to keep the type otherwise I can just use the :=
syntax.
Unfortunately I couldn't find any examples so I'm assuming this is just not possible?
If not, anyone knows if there's a plan to introduce such syntax in future releases?
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With