3 ms·
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.
by jamestimmins 5y ago
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.
- sk0g 5y agoIs 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.
- syntaxfree 5y agoOverloading the asterisk is always weird because multiplication is expected to be associative etc etc.
- ts4z 5y agotime.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.
- ts4z 5y ago(As noted elsewhere it's nanoseconds.)
- xyzzy_plugh 5y agoIt's not overloaded. It's a unit. You can just type time.Sleep(time.Second) but this reads nicely time.Sleep(3 * time.Minute)
- rwcarlsen 5y agoIt's not really overloading. it is associative: 2*time.Hour+1*time.second == time.Second+time.Hour*2
- wtallis 5y agoI believe that's illustrating commutativity, not associativity.
- thaumasiotes 5y agoThe 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.
- Laremere 5y agoThere is no operator overloading here. The type Duration is effectively an int64: https://pkg.go.dev/time#Duration https://pkg.go.dev/time#Duration
- vitus 5y agoI'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.)
- thaumasiotes 5y agoBut 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?
- cwojno 5y agoHaving used it extensively, it's actually quite nice.