In Go, how can I automatically force a loop index to uint?

I have several functions that take uint as their input:

 func foo(arg uint) {...} func bar(arg uint) {...} func baz(arg uint) {...} 

I have a loop whose limits are equal to uint constants of value

 const ( Low = 10 High = 20 ) 

In the next cycle, how can I say that I want to be uint ? The compiler complains that it is an int .

 for i := Low; i <= High; i++ { foo(i) bar(i) baz(i) } 

I really don't want to call uint(i) for every function call, and the following is correct, but it makes me feel dirty:

 var i uint for i = Low; i <= High; i++ { foo(i) bar(i) baz(i) } 
+4
source share
2 answers
 for i := uint(Low); i < High; i++ { ... } 

also note that uint() not a function call and, when applied to constants and (I believe) integers of the same size, happens completely at compile time.

Alternatively, although I would stick to the above, you can enter your constants.

 const ( Low = uint(10) High = uint(20) ) 

then i := Low will also be uint . In most cases, I would stick with untyped constants.

+10
source
 for i := uint(Low); i <= High; i++ { //EDIT: cf. larsmans' comment foo(i) bar(i) baz(i) } 

Playground

Or define the constants to be entered:

 const ( Low uint = 10 High uint = 20 ) ... for i := Low; i <= High; i++ { foo(i) bar(i) baz(i) } 

Playground

+8
source

All Articles