douzhao9608 2018-03-26 18:33
浏览 1105
已采纳

int * time.Second何时工作,什么时候在golang中不工作?

Why does time.Sleep(5 * time.Second) work fine, but:

x := 180
time.Sleep(15 / x * 60 * time.Second)

does not? I get a type mismatch error (types int64 and time.Duration). Given the error, I understand more of why the latter fails than why the former succeeds.

  • 写回答

1条回答 默认 最新

  • dsgdfg30210 2018-03-26 18:36
    关注

    In Go, a numeric literal (e.g. 60) is an untyped constant. That means it will be silently coerced to whatever type is appropriate for the operation where it's being used. So when you say:

    var x := 5 * time.Second
    

    Then the type is inferred from time.Second to be a time.Duration, and thus the literal 5 is also treated as a time.Duration. If there's nothing to infer a type from, it will assume a type ("bool, rune, int, float64, complex128 or string") and use that. So:

    x := 180
    

    Yields x with a type of int.

    However, when you do some operation involving something with a type - like, say a variable x that is an int - then you have two types and one must be converted for the operation to be legal.

    So, to the original question "When does int * time.Second work and when does it not in golang?", int * time.Second actually never works in Go. But 5 * time.Second isn't the same as int * time.Second.

    This is touched on in the Go tour:

    An untyped constant takes the type needed by its context.

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

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳