英文:
Use of variable in 'for' loop is not recognized in Go
问题
我正在开发Go语言,并运行以下for循环:
// 定义初始值
i := 0
for {
// 根据迭代获取随机数据
data, i := GiveRandomData(i)
// 保存到数据库
response, err := SaveToDatabase(data)
if err != nil { log.Fatal(err) }
fmt.Println(response)
}
然而,当编译这个程序时,我得到以下错误:
.\main.go:26: i declared and not used
Go编译器似乎没有意识到i
变量在下一次循环中被返回给函数。在这个函数内部,i
变量的值会改变。
我应该怎么做才能消除这个编译错误,或者让Go理解这个变量在这个无限for循环的下一次迭代中是被使用的呢?
英文:
I'm developing in Go and I run the following for loop:
// Define Initial Value
i := 0
for {
// Get random data based on iteration
data, i := GiveRandomData(i)
// Save to database
response, err := SaveToDatabase(data)
if err != nil { log.Fatal(err) }
fmt.Println(response)
}
However, when compiling this program, I get the following error:
> .\main.go:26: i declared and not used
The Go compiler doesn't seem to recognise that the i
variable is given back to the function in the next loop. Inside this function, the I
variable changes value.
What should I do to get rid of this compilation error or to let Go understand that this variable is not unused, but used in the next iteration of this endless for loop?
答案1
得分: 8
Go编译器似乎没有意识到在下一个循环中将i
变量返回给函数。在这个函数内部,I
变量的值发生了变化。
不,i
的值没有改变;:=
声明了一个新的i
。(Go允许你这样做是因为data
也是新的。)如果要给它赋值,你需要单独声明data
:
var data RandomDataType
data, i = GiveRandomData(i)
或者给新的i
一个临时名称:
data, next := GiveRandomData(i)
i = next
英文:
> The Go compiler doesn't seem to recognise that the i
variable is given back to the function in the next loop. Inside this function, the I
variable changes value.
No, i
does not change value; :=
declares a new i
. (Go allows you to do this because data
is also new.) To assign to it instead, you’ll need to declare data
separately:
var data RandomDataType
data, i = GiveRandomData(i)
Or give the new i
a temporary name:
data, next := GiveRandomData(i)
i = next
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论