Home > Backend Development > Golang > Can I Explicitly Type a Variable in a Go For Loop\'s Initialization Statement?

Can I Explicitly Type a Variable in a Go For Loop\'s Initialization Statement?

Patricia Arquette
Release: 2024-11-27 17:03:12
Original
872 people have browsed it

Can I Explicitly Type a Variable in a Go For Loop's Initialization Statement?

Variable Declaration in the Initialization Statement of a For Loop

A common question for Go beginners is regarding variable declaration in the initialization statement of a for loop. While you can write a loop like for i := 0; i < 10; i , specifying a type explicitly within the initialization statement seems impossible.

Attempting to specify a type directly within the initialization, such as for var i int64 = 0; i < 10; i , will result in an error. Contrary to expectations, you must declare the variable outside of the loop initialization and assign it within:

var i int64
for i = 0; i < 10; i++ {
    // i here is of type int64
}
Copy after login

The language specification for a for loop states that the initialization statement may be a short variable declaration, which assigns a value (e.g., i := 0) but not a full variable declaration (var i = 0).

The reason behind this is likely to maintain language simplicity. However, it's worth noting that you can achieve a similar result by using a type conversion:

for i := int64(0); i < 10; i++ {
    // i here is of type int64
}
Copy after login

The above is the detailed content of Can I Explicitly Type a Variable in a Go For Loop\'s Initialization Statement?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template