在Go语言中,’for’循环中的变量使用不被识别。

huangapple go评论104阅读模式
英文:

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

huangapple
  • 本文由 发表于 2017年7月17日 15:04:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/45137897.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定