普通网友 2015-03-17 12:37
浏览 242
已采纳

为什么在Go中将两个time.durations相除会导致另一个time.duration?

I don't understand what it means to divide a time.Duration in Go.

For example, this is super lovely:

d,_ := time.ParseDuration("4s")
fmt.Println(d/4)

print 1s. Which is ace, because (naively) 4 seconds divided by 4 is 1 second.

It gets a little confusing though when we find out that the 4 in the denominator has to be a duration. So although:

d1 := time.Duration(4)
fmt.Println(d/d1)

also prints 1s, we know that d1 is actually 4ns and I'm entirely unconvinced that 4 seconds divided by 4 nanoseconds is 1 second.

I'm confused because a duration divided by duration should be dimensionless (I think, right?), whereas a duration divided by a dimensionless number should have units of time.

And I know that type != unit, but I'm clearly misunderstanding something, or quite possibly a set of things. Any help to clear this up would be most appreciated!

Here is a go playground of the above examples. https://play.golang.org/p/Ny2_ENRlX6. And just for context, I'm trying to calculate the average time between events. I can fall back to using floats for seconds, but am trying to stay in time.Duration land.

  • 写回答

3条回答 默认 最新

  • dongza6247 2015-03-17 12:44
    关注

    It is so because time.Duration is int64. See documentation of time package.

    You make a division of 4000000000 (4s) by 4 (4ns) and you get 1000000000 (1s). You should look at the operations as they where integers not typed values. Type Duration make it look like a physical value but for division operation it is just a number.

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

报告相同问题?

悬赏问题

  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题
  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信