for循环的init语句中的变量声明 [英] variable declaration in init statement of for loop
问题描述
另外一个初学者对于golang的问题:
我可以这样写:
for i:= 0;我< 10; i ++ {}
但是如果我想要 i
作为 int64
的特定类型,显然我不应该写:
for var i int64 = 0;我< 10; i ++ {}
我很惊讶我无法在for循环的start语句中指定一个类型。我需要写这样的内容:
pre code $ var i int64
for i = 0;我< 10; i ++ {}
我在这里错过了一个观点吗?有什么解释吗?
一个for循环的语言规范指出: init语句可能是一个简短的变量声明
,它是 i:= 0
格式的赋值,但不是格式 var i = 0
。至于背后的原因 - 我猜语言简单。看到这里: http://golang.org/ref/spec#For_statements
顺便说一句 can 可以这样做:
for我:= int64(0);我< 10; i ++ {
//我这里的类型是int64
}
Yet another beginner's question for golang:
I can write:
for i := 0; i < 10; i++ {}
But if I want i
to be of a specific type as int64
, apparently I am not supposed to write:
for var i int64 = 0; i < 10; i++ {}
I am surprised that I cannot specify a type in the start statement of the for loop. I need to write something like this:
var i int64
for i = 0; i < 10; i++ {}
Am I missing a point here? Is there any explanation for it?
The language specification for a for loop states that: The init statement may be a short variable declaration
, which is assignment of the form i := 0
but not a declaration of the form var i = 0
. As for the reason behind this - I'm guessing language simplicity. See here: http://golang.org/ref/spec#For_statements
BTW You can do something like this:
for i := int64(0); i < 10; i++ {
// i here is of type int64
}
这篇关于for循环的init语句中的变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!