douliang4858 2017-03-05 06:51
浏览 29
已采纳

按时间的分数进行睡眠

Can someone tell me why this works:

s := time.Hour/73.0
fmt.Println("sleeping: ", s)
time.Sleep(s)

But this fails:

d := 73.0
s := time.Hour/d
fmt.Println("sleeping: ", s)
time.Sleep(s)

This is the error:

invalid operation: time.Hour / d (mismatched types time.Duration and float64)
  • 写回答

1条回答 默认 最新

  • drctyr2869 2017-03-05 08:34
    关注

    This line:

    s := time.Hour/73.0
    

    Is a short variable declaration, where the right hand side expression is: time.Hour / 73.0. time.Hour is a typed constant from the time package, its type is time.Duration; and 73.0 is an untyped numeric constant which when used in an expression, will take the appropriate type if possible. Since time.Duration has int64 as its underlying type, the constant 73.0 can be converted to time.Duration without loss of precision, so that will happen, and the constant expression time.Hour / time.Duration(73.0) will be executed.

    The other line:

    d := 73.0
    s := time.Hour/d
    

    The first line is a short variable declaration, where the type of d will be inferred from the right hand side expression, which is an untyped numeric constant (given with a floating point literal to be exact). Since a type is needed, its default type will be used, which is float64. So d will be a variable of type float64.

    The short variable declaration in the next line: time.Hour / d, here time.Hour is again a value of type time.Duration, but you attempt to divide it by a value of type float64, that is not allowed in Go.

    To make it work, you have to explicitly convert d to time.Duration:

    s := time.Hour / time.Duration(d)
    

    Or d must be of type time.Duration:

    d := time.Duration(73.0)
    s := time.Hour / d
    

    Or:

    var d time.Duration = 73.0
    s := time.Hour / d
    

    These wouldn't work if the value cannot be represented with time.Duration, for example 73.5 (because time.Duration has int64 underlying type). In this case you have to convert time.Hour to float64, perform the division and convert the result to time.Duration, e.g.:

    d := 73.5
    s := time.Duration(float64(time.Hour) / d)
    

    Read more details on the topic:

    Spec: Constants

    The Go Blog: Constants

    Why does 0.1 + 0.2 get 0.3 in Google Go?

    How does Go perform arithmetic on constants?

    Golang converting float64 to int error

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么