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

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

How can I change the for loop iterator type?

问题

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

  1. func main() {
  2. var val uint64 = 1234567890
  3. for i := uint64(1); i < val; i += 2 {
  4. if val%i == 0 {
  5. }
  6. }
  7. }

./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 (%).

  1. func main() {
  2. var val uint64 = 1234567890
  3. for i:=1; i&lt;val; i+=2 {
  4. if val%i==0 {
  5. }
  6. }
  7. }
  8. ./q.go:7: invalid operation: i &lt; val (mismatched types int and uint64)
  9. ./q.go:8: invalid operation: val % i (mismatched types uint64 and int)

答案1

得分: 37

你是指像这样的吗?

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

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

英文:

You mean something like this?

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

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

答案2

得分: 0

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

  1. package main
  2. func main() {
  3. var i, val uint64 = 1, 1234567890
  4. for i < val {
  5. if val % i == 0 {
  6. println(i)
  7. }
  8. i += 2
  9. }
  10. }

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

英文:

Another option is to use a "while" loop:

  1. package main
  2. func main() {
  3. var i, val uint64 = 1, 1234567890
  4. for i &lt; val {
  5. if val % i == 0 {
  6. println(i)
  7. }
  8. i += 2
  9. }
  10. }

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:

确定