Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Go, how can I automatically coerce my loop index into an uint?

Tags:

go

I have a few functions taking an uint as their input :

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

I have a loop whose limits are both constant uint values

const (
    Low = 10
    High = 20
)

In the following loop, how can I say I want i to be a uint ? The compiler complains about it being an int.

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

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

var i uint

for i = Low; i <= High; i++ {
    foo(i)
    bar(i)
    baz(i)
}
like image 284
Fabien Avatar asked Dec 02 '22 19:12

Fabien


2 Answers

for i := uint(Low); i < High; i++ {
    ...
}

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

Alternatively, though I'd stick with the above, you can type your constants.

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

then i := Low will also be a uint. I'd stick with untyped constants in most cases.

like image 199
cthom06 Avatar answered Dec 16 '22 04:12

cthom06


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

Playground

Or define the constants to be typed:

const (
        Low  uint = 10
        High uint = 20
)

...

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

Playground

like image 37
zzzz Avatar answered Dec 16 '22 04:12

zzzz