如何更改for循环的迭代器类型?

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

How can I change the for loop iterator type?

问题

Go在默认情况下使用int作为迭代器,但我想要使用uint64。我无法找到一种方法来改变Go中for循环迭代器的类型。有没有一种方法可以在for语句中内联地进行更改?当我尝试在循环中执行一些操作,比如取模运算(%)时,默认的int类型会引起问题。

func main() {
    var val uint64 = 1234567890
    for i := uint64(1); i < val; i += 2 {
        if val%i == 0 {
        }
    }
}

./q.go:7: invalid operation: i < val (mismatched types int and uint64)
./q.go:8: invalid operation: val % i (mismatched types uint64 and int)

英文:

Go uses int for the iterator by default from what I can tell, except I want uint64. I cannot figure out a way to change the type of for loop iterator in Go. Is there a way to do it inline with the for statement? The default type of int causes problems when I try to do something in the loop, like a mod operation (%).

func main() {                                                                                                                               
    var val uint64 = 1234567890                                                 
    for i:=1; i&lt;val; i+=2 {  
        if val%i==0 {
        }                                        
    }                                                                          
} 

./q.go:7: invalid operation: i &lt; val (mismatched types int and uint64)
./q.go:8: invalid operation: val % i (mismatched types uint64 and int)

答案1

得分: 37

你是指像这样的吗?

for i, val := uint64(1), uint64(1234567890); i<val; i+=2 {
    // 你的模运算
} 

http://play.golang.org/p/yAdiJu4pNC

英文:

You mean something like this?

for i, val := uint64(1), uint64(1234567890); i&lt;val; i+=2 {
    // your modulus operation
} 

http://play.golang.org/p/yAdiJu4pNC

答案2

得分: 0

另一个选项是使用“while”循环:

package main

func main() {                                                                 
   var i, val uint64 = 1, 1234567890
   for i < val {
      if val % i == 0 {
         println(i)
      }
      i += 2
   }                                                                          

} 

https://golang.org/ref/spec#For_condition

英文:

Another option is to use a "while" loop:

package main

func main() {                                                                 
   var i, val uint64 = 1, 1234567890
   for i &lt; val {
      if val % i == 0 {
         println(i)
      }
      i += 2
   }                                                                          
} 

https://golang.org/ref/spec#For_condition

huangapple
  • 本文由 发表于 2013年2月23日 01:56:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/15030327.html
匿名

发表评论

匿名网友

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

确定