在Go中,我如何自动将循环索引强制转换为uint类型?

huangapple go评论78阅读模式
英文:

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 &lt;= 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 &lt;= 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 &lt; 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)
}

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

英文:
for i := uint(Low); i &lt;= High; i++ { //EDIT: cf. larsmans&#39; 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 &lt;= High; i++ {
        foo(i)
        bar(i)
        baz(i)
}

Playground

huangapple
  • 本文由 发表于 2013年4月10日 22:02:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/15928071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定