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)
}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With