Is it possible to declare multiple variables at once using Golang?
For example in Python you can type this:
a = b = c = 80
and all values will be 80.
Is it possible to declare multiple variables at once using Golang?
For example in Python you can type this:
a = b = c = 80
and all values will be 80.
In terms of language specification, this is because the variables are defined with:
(From "Variable declaration")
A list of identifiers for one type, assigned to one expression or ExpressionList.
Try this in the go-playground: https://play.golang.org/
Yes you can and it is slightly more nuanced than it seems.
To start with, you can do something as plain as:
You can use the same syntax in function parameter declarations:
Then comes the short-hand syntax for declaring and assigning a variable at the same time.
An oft-encountered pattern in Golang is:
So you can assign to already-defined variables on the left side of the
:=
operator, so long as at least one of the variables being assigned to is new. Otherwise it's not well-formed. This is nifty because it allows us to reuse the same error variable for multiple API calls, instead of having to define a new one for each API call. But guard against inadvertent use of the following:Yes, you can:
You can do something sort of similar for inline assignment, but not quite as convenient: