Mike Dewar
Mike Dewar

Reputation: 11115

Why does dividing two time.durations in Go result in another 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.

Upvotes: 5

Views: 2252

Answers (3)

Grzegorz Żur
Grzegorz Żur

Reputation: 49241

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.

Upvotes: 4

Volker
Volker

Reputation: 42458

There are no units attached to a time.Duration. A time.Duration represents the physical concept of a duration (measured in seconds and having a unit) by providing a distinct type, namely the time.Duration type. But technically it is just a uint64.

If you try to attach actual units to types you'll enter unit-hell: What would a (time.Duration * time.Duration)/acceleration.Radial * mass.MetricTon be? Undefined most probably.

Upvotes: 3

Ben Darnell
Ben Darnell

Reputation: 22154

Mathematically, you're correct: dividing two time.Durations should result in a dimensionless quantity. But that's not how go's type system works. Any mathematical operation results in a value of the same type as the inputs. You'll have to explicitly cast the result of the division to an int64 to get an "untyped" quantity.

Upvotes: 6

Related Questions