doujingqu3030 2012-10-05 11:45
浏览 306
已采纳

如何在go中使用自定义int类型的range?

I have

type DocId int

func foo(documents []String) {
    for i := range documents {
        id := DocId(i)
        ...
    }
}

How do I get rid of the explicit conversion line? DocIds are meant to be the type that indexes individual documents.

What I want is more like:

func foo(documents []String) {
    for id := range documents {
        ... // id gets used as the DocId that it damn well *IS*
    }
}

Which gives me 'invalid operation: ... (mismatched types int and DocId)' when I attempt to use the id from range as a DocId, even though DocId is an int.

  • 写回答

2条回答 默认 最新

  • donglian5309 2012-10-05 12:14
    关注

    Only untyped constant can be automatically converted in the right type.

    You can find examples where the cast is not needed like in this thread, for untyped constant. From the specs:

    if one operand is an untyped constant and the other operand is not, the constant is converted to the type of the other operand

    But here, range explicitly assign iteration values to the corresponding iteration variables (i int, T a[i]), which makes i and int. (from spec "For statement")

    For all the other case, an explicit cast is required.
    The "Conversion" section of the specs doesn't mention an "automatic" type conversion (as opposed to automatic interface conversion, which happens all the time: interface{}).

    This thread adds

    type A int
    type B int
    
    ...
    
    var a A = 5
    var b B = a    // Compiler ERROR!!!!!!
    

    Essentially, since (nearly) all types are unique, even two types with the same underlying representation and primitive operations are unassignable without a cast. [...]
    This makes the language type-safe by forcing you to explicitly tell the compiler when you want the conversion to happen.

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

报告相同问题?

悬赏问题

  • ¥30 计算机硬件实验报告寻代
  • ¥15 51单片机写代码,要求是图片上的要求,请大家积极参与,设计一个时钟,时间从12:00开始计时,液晶屏第一行显示time,第二行显示时间
  • ¥15 用C语言判断命题逻辑关系
  • ¥15 原子操作+O3编译,程序挂住
  • ¥15 使用STM32F103C6微控制器设计两个从0到F计数的一位数计数器(数字),同时,有一个控制按钮,可以选择哪个计数器工作:需要两个七段显示器和一个按钮。
  • ¥15 在yolo1到yolo11网络模型中,具体有哪些模型可以用作图像分类?
  • ¥15 AD9910输出波形向上偏移,波谷不为0V
  • ¥15 淘宝自动下单XPath自动点击插件无法点击特定<span>元素,如何解决?
  • ¥15 曙光1620-g30服务器安装硬盘后 看不到硬盘
  • ¥15 抖音直播广场scheme