在Golang中不能识别的循环中使用变量 [英] use of variable in for loop not recognized in Golang

查看:477
本文介绍了在Golang中不能识别的循环中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  //定义初始值
i := 0

for {
//获取基于迭代的随机数据
data,i:= GiveRandomData(i)

//保存数据库
response,err:= SaveToDatabase(data)
$ b $ if err!= nil {log.Fatal(err)}
fmt.Println(response)
}

但是,在编译这个程序时,我得到以下错误:


.\main.go:26:我声明并未使用


Golang编译器似乎没有认识到i变量在下一个循环中被返回给函数。在这个函数里,I变量改变了值。

我应该怎么做才能摆脱这个编译错误,或者让golang明白这个变量不是未被使用的,而是被用在这个无尽的循环的下一个迭代?

解决方案


Golang编译器似乎不能识别i变量在下一个循环中被返回给函数。


不, i 确实不改变价值; := 声明一个新的 i 。 (Go允许你这样做,因为 data 也是新的。)要分配给它,你需要声明 data b
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $变量数据随机数据类型
数据,i = GiveRandomData(i)

code>

或给新的 i 一个临时名称:

  data,next:= GiveRandomData(i)
i = next


I'm developing in golang 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 Golang 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 golang understand that this variable is NOT unused but used in the next iteration of this endless for loop?

解决方案

The Golang 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

这篇关于在Golang中不能识别的循环中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆