douyue7536 2013-04-10 14:02
浏览 49
已采纳

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

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)
}
  • 写回答

2条回答 默认 最新

  • duannuci4008 2013-04-10 14:10
    关注
    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 pychram安装jupyter插件
  • ¥60 悬赏破解越狱iphone4s中360保险箱密码遗忘
  • ¥20 ARKts悬浮窗和快捷方式问题
  • ¥15 linux中nginx服务器提示not found on accelerator,如何解决?(语言-php|操作系统-linux)
  • ¥15 comparecluster没有办法kegg
  • ¥15 远程访问linux主机超时
  • ¥15 odoo17存货管理优势于中国国内该行业传统ERP或MES的详细解读和举例
  • ¥15 CPU卡指令整合指令数据都在图片上
  • ¥15 odoo17处理受托加工产品
  • ¥15 如何用MATLAB编码图三的积分