英文:
In Go, how can I automatically coerce my loop index into an uint?
问题
我有几个函数以uint
作为它们的输入:
func foo(arg uint) {...}
func bar(arg uint) {...}
func baz(arg uint) {...}
我有一个循环,其限制都是常量uint
值
const (
Low = 10
High = 20
)
在下面的循环中,我该如何表达我希望i
是一个uint
?编译器抱怨它是一个int
。
for i := Low; i <= High; i++ {
foo(i)
bar(i)
baz(i)
}
我真的不想在每个函数调用上调用uint(i)
,而且做以下操作是正确的,但让我感觉很不舒服:
var i uint
for i = Low; i <= High; i++ {
foo(i)
bar(i)
baz(i)
}
英文:
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)
}
答案1
得分: 10
for i := uint(Low); i < High; i++ {
...
}
还要注意uint()
不是一个函数调用,当应用于常量和(我相信)相同大小的有符号整数时,它完全在编译时发生。
或者,虽然我会坚持上面的方法,你可以为常量指定类型。
const (
Low = uint(10)
High = uint(20)
)
然后i := Low
也将是一个uint
。在大多数情况下,我会坚持使用无类型常量。
英文:
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.
答案2
得分: 8
for i := uint(Low); i <= High; i++ { //EDIT: cf. larsmans' comment
foo(i)
bar(i)
baz(i)
}
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)
}
英文:
for i := uint(Low); i <= High; i++ { //EDIT: cf. larsmans' comment
foo(i)
bar(i)
baz(i)
}
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论