Home  >  Article  >  Backend Development  >  Can You Initialize Multiple Variables of Different Types in Go Without Short Declaration Syntax?

Can You Initialize Multiple Variables of Different Types in Go Without Short Declaration Syntax?

DDD
DDDOriginal
2024-10-30 12:13:03265browse

 Can You Initialize Multiple Variables of Different Types in Go Without Short Declaration Syntax?

Multiple Variable Initialization in Go without Short Declaration Syntax

In Go, declaring and initializing multiple variables of different types in one line can be done without using the short declaration syntax (:=). However, this requires omitting the types of the variables.

Example:

<code class="go">var i, s = 2, "hi"
fmt.Println(i, s)</code>

Output (try it on the Go Playground):

2 hi

The short variable declaration (:=) is a shorthand for a regular variable declaration with initializer expressions but no types.

Syntax:

ShortVarDecl = IdentifierList ":=" ExpressionList .

Equivalent Syntax:

"var" IdentifierList "=" ExpressionList .

Limitations:

Without omitting the types, it is not possible to declare multiple variables of different types in one line. The syntax for variable declaration requires a single type for an identifier list with an expression list.

Conclusion:

While omitting the types allows for multiple variable initialization in one line, it is generally recommended to use multiple lines for different types to improve readability. Alternatively, you can explicitly state the types on the right side of the assignment:

<code class="go">var i, s = int(2), string("hi")</code>

The above is the detailed content of Can You Initialize Multiple Variables of Different Types in Go Without Short Declaration Syntax?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn