How to loop in Golang without using the iterator?

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

How to loop in Golang without using the iterator?

问题

我知道这段代码是有效的。

for i := range []int{1, 2, 3....} {
    fmt.Println(i)
}

但是,如果我想要像下面这样做:

for i := range []int{1, 2, 3....} {
    code := GenNewCode()
    Insert(code)
}

我会得到一个错误,提示i没有被使用。有没有一种方法可以在不出现上述错误的情况下实现这个目标?
(如果这是一个愚蠢的问题,请原谅,我只是在学习一点 Golang。)

英文:

I know this works.

for i :=range []int{1, 2, 3....} {
    fmt.Println(i)
}

But If I want to do something like:

for i :=range []int{1, 2, 3....} {
    code = GenNewCode()
    Insert(code)
}

I get an error that i was not used.
Is there a way I can do it without getting the above error?
(Pardon me if this is a silly question, I am just learning Golang a bit.)

答案1

得分: 1

你可以使用空白标识符来忽略这些内容:_

for _ := range []int{1, 2, 3} {
    code = GenNewCode()
    Insert(code)
}

或者可以使用(通过JimB的评论)

for range []int{1, 2, 3}{
    code = GenNewCode()
    Insert(code)
}
英文:

You can ignore such things by using the blank identifier: _

for _ := range []int{1, 2, 3} {
    code = GenNewCode()
    Insert(code)
}

Or one can use (via JimB's comment)

for range []int{1, 2, 3}{
code = GenNewCode()
    Insert(code)
}

huangapple
  • 本文由 发表于 2016年12月22日 03:13:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/41270276.html
匿名

发表评论

匿名网友

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

确定