Re:Please put units in names
by jamestimmins on Sunday March 20, 2022 @11:01PM
(#30749685)
I'm not sure why but I have a visceral, negative response to this. It might be the best solution, but it definitely /feels/ like the worst of all the worlds.
[ Parent
| on HN ]
Is it? In most languages you do something like `time.Sleep(1 * 1e6)` instead at which point it could be a second, a few minutes, a day, who really knows?
I'm just not seeing any major downsides of this, keep in mind `time.Second` isn't the only one of its kind, you have millisecond, minute, hour, etc etc.
Having used it extensively, it's actually quite nice.
Re:Please put units in names
by syntaxfree on Sunday March 20, 2022 @11:05PM
(#30749730)
Overloading the asterisk is always weird because multiplication is expected to be associative etc etc.
I'm not sure I follow.
2 * 3 * time.Second is the same whether you group 2 * (3 * time.Second) or (2 * 3) * time.Second (namely, the implicit grouping under left-associativity).
You wouldn't normally write time.Sleep(time.Second * time.Second) because your units wouldn't work out. (Apparently you can write that in Golang; it's just very sketchy and results in a 30-year sleep.)
Re:Please put units in names
by thaumasiotes on Monday March 21, 2022 @12:26AM
(#30750257)
But from a mathematical point of view, the relationship between a unit and its coefficient is that you're multiplying them together. Why would it be weird to overload the multiplication operator to represent multiplication?
There is no operator overloading here. The type Duration is effectively an int64: https://pkg.go.dev/time#Duration
Re:Please put units in names
by xyzzy_plugh on Sunday March 20, 2022 @11:08PM
(#30749761)
It's not overloaded. It's a unit. You can just type
time.Sleep(time.Second)
but this reads nicely time.Sleep(3 * time.Minute)time.Second*1 gets the same value; it's not overloaded. Well, ok, so what actually happens is that time.Second is a time.Duration, and Duration*int yields Duration (and int*Duration yields Duration).
But the value of time.Second is actually a Duration with value 1000000, IIRC -- it's microseconds. It's just the type that's special, and the int handling here is general over a lot of types.
It really is nice in practice.
(As noted elsewhere it's nanoseconds.)
It's not really overloading. it is associative:
2*time.Hour+1*time.second == time.Second+time.Hour*2I believe that's illustrating commutativity, not associativity.
Re:Please put units in names
by thaumasiotes on Monday March 21, 2022 @12:28AM
(#30750273)
The illustration is wrong, but the claim is correct; multiplication between units and scalars is just as associative as you'd expect. Multiplying one kilowatt by an hour gives you exactly the same result as multiplying 1 by a kilowatt-hour.