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

DDD
Release: 2024-10-30 12:13:03
Original
272 people have browsed it

 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>
Copy after login

Output (try it on the Go Playground):

2 hi
Copy after login

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

Syntax:

ShortVarDecl = IdentifierList ":=" ExpressionList .
Copy after login

Equivalent Syntax:

"var" IdentifierList "=" ExpressionList .
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!