Home > Article > Backend Development > How to Declare Multiple Variables of Different Types in One Line in Go?
Multiple Variables of Different Types in One Line in Go (Without Short Variable Declaration Syntax)
Declaring and initializing multiple variables of the same type in one line in Go is straightforward, but doing so with variables of varying types presents a challenge. This is because the standard variable declaration syntax, var a, b string = "hello", "world", only allows for variables of the same type.
While the short variable declaration syntax, c, d, e := 1, 2, "whatever", enables the declaration of variables of different types in a single line, it sacrifices explicit type information. If you prefer to retain type definitions, the default variable declaration syntax must be employed.
Unfortunately, it is not possible to explicitly specify the types of multiple variables of different types in a single line. The syntax for variable declaration requires a single type or no type at all for a given set of identifiers.
To declare multiple variables of different types in one line, omit the types entirely:
<code class="go">var i, s = 2, "hi"</code>
This effectively becomes a shorthand for the longer syntax:
<code class="go">var i int = 2 var s string = "hi"</code>
As seen above, the short variable declaration syntax is merely a compact way of declaring variables without specifying types.
Note that declaring multiple variables with varying types on a single line may not provide any significant advantages. While it reduces the number of lines of code, it can compromise readability. Consider using separate lines for each variable declaration to enhance code clarity.
The above is the detailed content of How to Declare Multiple Variables of Different Types in One Line in Go?. For more information, please follow other related articles on the PHP Chinese website!