Hacker News new | ask | show | jobs
by aric 3866 days ago
1. I don't see how.

2. Impure?

3. That's the point. It's to force people to stop using maps as if they're sorted.

4. Why would you want to rely on the arbitrary nature of a hash table for order?

5. That's the best type of boilerplate. It's short. It brings clarity. You might not need custom sort functions. The sort package supports basic types, which you'd use if you're keeping track of an index with []int for instance. https://golang.org/pkg/sort/

1 comments

It's not about relying on hash tables for order. It's about the invariant that traversing a hash table N times will produce the same ordering each time, as long as the hash table is not mutated, even though that ordering is unpredictable.

Disclaimer: I've never used this feature myself and I sympathize with the desire on the part of the Go designers to avoid accidental de facto stabilization of hash table iteration order--though it sounds like it could have been done without drawbacks by randomizing at process start.

It is to prevent hash tables being relied on for order. Randomization was added so maps aren't treated as invariant. The behavior in a range of a map is no less correct to be changing (in Go) rather than unchanging (in other languages). In other words, invariant relative to what? It's not too important. It's one of numerous ways Go promotes clearer design, at least in my eyes, to have disorder represent unordered and order represent ordered.
This is a very philosophical comment, but I'm not seeing a specific, practical advantage that randomizing on every iteration confers over randomizing on process start.

Can you provide one? (I'm genuinely curious.)

It's no more philosophical than saying the alternative is proper. Uniformity of expectations seems more practical to me. In contrast, I wouldn't see an advantage in map ranges ever staying the same even per process. There's no reason to promote that reliance.
Well I gave 5 reasons up at the top :)

But from a philosophical perspective, referential transparency is a big one. We should prefer to make functions referentially transparent, because it makes them easier to reason about. Sometimes we do not, because it would be too slow or too awkward. But in this case, the loss is gratuitous.

Or to put it concretely: in Python (and every other language), we have the fact that `dict.keys() == dict.keys()`. In Go, this is true sometimes. Doesn't that seem weird to you?

But there is one, which the original post in the thread described: you could for example convert a map of arrays to a flat array by iterating over it repeatedly and printing the ith element of each array. This doesn't work if every loop over the elements gets a different ordering.