猿问

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

我有几个函数将 anuint作为输入:


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)

}


holdtom
浏览 219回答 2
2回答

www说

for i := uint(Low); i < High; i++ {&nbsp; &nbsp; ...}还要注意,这uint()不是函数调用,当应用于常量和(我相信)相同大小的有符号整数时,完全在编译时发生。或者,虽然我会坚持上述内容,但您可以输入常量。const (&nbsp; &nbsp; Low = uint(10)&nbsp; &nbsp; High = uint(20))那么i := Low也将是一个uint. 在大多数情况下,我会坚持使用无类型常量。

三国纷争

for i := uint(Low); i <= High; i++ { //EDIT: cf. larsmans' comment&nbsp; &nbsp; &nbsp; &nbsp; foo(i)&nbsp; &nbsp; &nbsp; &nbsp; bar(i)&nbsp; &nbsp; &nbsp; &nbsp; baz(i)}或者定义要输入的常量:const (&nbsp; &nbsp; &nbsp; &nbsp; Low&nbsp; uint = 10&nbsp; &nbsp; &nbsp; &nbsp; High uint = 20)...for i := Low; i <= High; i++ {&nbsp; &nbsp; &nbsp; &nbsp; foo(i)&nbsp; &nbsp; &nbsp; &nbsp; bar(i)&nbsp; &nbsp; &nbsp; &nbsp; baz(i)}
随时随地看视频慕课网APP

相关分类

Go
我要回答