mfisch
mfisch

Reputation: 989

How can I change the for loop iterator type?

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<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)

Upvotes: 21

Views: 11576

Answers (2)

Zombo
Zombo

Reputation: 1

Another option is to use a "while" loop:

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

Upvotes: 0

the system
the system

Reputation: 9336

You mean something like this?

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

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

Upvotes: 39

Related Questions