Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the for loop iterator type?

Tags:

go

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)
like image 323
mfisch Avatar asked Feb 22 '13 17:02

mfisch


People also ask

Can we change I in for loop?

A for loop assigns a variable (in this case i ) to the next element in the list/iterable at the start of each iteration. This means that no matter what you do inside the loop, i will become the next element. The while loop has no such restriction.

How do you change iterable in Python?

Python iter() is an inbuilt function that is used to convert an iterable to an iterator. It offers another way to iterate the container i.e access its elements. iter() uses next() for obtaining values. The iter() method returns the iterator for the provided object.

Does range based for loop use iterator?

Range-Based 'for' loops have been included in the language since C++11. It automatically iterates (loops) over the iterable (container).

How do you change the start point of a for loop in Python?

Use n+1 in Place of n in the range() Function to Start the for Loop at an Index 1 in Python. This method can be implemented by using the start value as 1 and the stop value as n+1 instead of default values 0 and n , respectively.


1 Answers

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

like image 62
the system Avatar answered Nov 03 '22 00:11

the system