doujiao2000 2018-08-29 05:54
浏览 26
已采纳

为什么需要将变量转换为持续时间而不是原始整数? [重复]

This question already has an answer here:

If I want to sleep for 2 seconds I can do the following:

time.Sleep(2 * time.Second)

but when I do:

test := 2
time.Sleep(test * time.Second)

It throws the error

invalid operation: test * time.Second (mismatched types int and time.Duration)

I can fix this by casting test like so: time.Sleep(time.Duration(rand.Intn(5)) * time.Second) but i'm wondering why it is that I need to wrap it in time.Duration when it's a variable and not when it's a raw value?

</div>
  • 写回答

1条回答 默认 最新

  • dongxuan1660 2018-08-29 06:00
    关注

    The difference is that you pass a const in the first case of 2 * time.Second and a var in the second case where you declare test := 2. Read this blog post about constants in Go for more details.

    Basically, a const literal in the code will be converted to the type that makes sense for the surrounding expression. In the first case 2 * time.Duration this means that the 2 is converted to a time.Duration while in the second case test := 2 the 2 is assigned to the test variable. This means that the type inference happens at that point, giving test the type int which is the default type for the literal 2. If you used the literal 2.0 instead, the test variable would have type float64 instead. However, the expression test * time.Second has the type of test already set and it is different from the type of time.Duration which is why you get that compiler error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决