Home >Backend Development >Golang >How can you declare multiple variables of different types in Go with explicit type information?
Multi-Variable Declarations in Go
In Go, it's not directly possible to declare and initialize multiple variables of different types in one line while specifying their types explicitly. Using the short variable declaration syntax (":=") is viable for this purpose, but what if you want to retain the explicit type information?
However, there is an alternative approach that allows you to omit the types and still have multiple variables declared on the same line:
<code class="go">var i, s = 2, "hi"</code>
This syntax is valid because omitting the types implies that the variables will be assigned values of the same type as their respective expressions. In the example above, i will be an int and s will be a string because of the assigned values.
It's worth noting that this is equivalent to a regular variable declaration with initializer expressions but no types:
<code class="go">var i = 2 var s = "hi"</code>
Note that this approach differs from the short variable declaration syntax, which uses := as shorthand for this longer form.
To adhere to the explicit type declaration requirement, an alternative approach is to provide the types on the right side of the assignment:
<code class="go">var i, s = int(2), string("hi")</code>
However, it's generally good practice to keep related variable declarations and initializations on separate lines for improved readability and maintainability.
The above is the detailed content of How can you declare multiple variables of different types in Go with explicit type information?. For more information, please follow other related articles on the PHP Chinese website!