douque2016 2013-10-12 18:55
浏览 564
已采纳

time.Millisecond * int混乱

In the below example, if the 1000's are both int's (which I think they are) why would the bottom fail to compile?

//works
time.Sleep(1000 * time.Millisecond)

//fails
var i = 1000
time.Sleep(i * time.Millisecond)
  • 写回答

4条回答 默认 最新

  • duanmuyao0463 2013-10-12 19:12
    关注

    Operators

    Operators combine operands into expressions.

    Comparisons are discussed elsewhere. For other binary operators, the operand types must be identical unless the operation involves shifts or untyped constants. For operations involving constants only, see the section on constant expressions.

    Except for shift operations, if one operand is an untyped constant and the other operand is not, the constant is converted to the type of the other operand.

    For example, using the "*" (multiplication) operator,

    package main
    
    import (
        "time"
    )
    
    func main() {
    
        // works - 1000 is an untyped constant
        // which is converted to type time.Duration
        time.Sleep(1000 * time.Millisecond)
    
        // fails - v is a variable of type int
        // which is not identical to type time.Duration
        var v = 1000
        // invalid operation: i * time.Millisecond (mismatched types int and time.Duration)
        time.Sleep(v * time.Millisecond)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法