When iterating through the returned map in the code, returned by the topic function, the keys are not appearing in order.
How can I get the keys to be in order / sort the map so that the keys are in order and the values correspond?
Here is the code.
The Go blog: Go maps in action has an excellent explanation.
Here's my modified version of example code: http://play.golang.org/p/dvqcGPYy3-
Output:
While most of these answers are correct, I often find a C-style for-loop to be the most simple solution (though only if your keys are a series of
int
s):Output:
According to the Go spec, the order of iteration over a map is undefined, and may vary between runs of the program. In practice, not only is it undefined, it's actually intentionally randomized. This is because it used to be predictable, and the Go language developers didn't want people relying on unspecified behavior, so they intentionally randomized it so that relying on this behavior was impossible.
What you'll have to do, then, is pull the keys into a slice, sort them, and then range over the slice like this:
If, like me, you find you want essentially the same sorting code in more than one place, or just want to keep the code complexity down, you can abstract away the sorting itself to a separate function, to which you pass the function that does the actual work you want (which would be different in each place, of course).
Given a map with key type
K
and value typeV
, represented as<K>
and<V>
below, the common sort function might look something like this:Then call it with the input map and a function (taking
k <K> v <V>
as input arguments) that is called over the map elements in sorted-key order.So, a version of the code in the answer posted by Mingu might look like:
The
sortedMapIntString()
function can be re-used for anymap[int]string
(assuming the same sort order is desired), keeping each use to just two lines of code.Downsides include:
Other languages have various solutions:
<K>
and<V>
(to denote types for the key and value) looks a bit familiar, that code template is not terribly unlike C++ templates.range
a first-class type such that it could be substituted with a customordered-range
(in place ofrange
in the original code), I think some other languages provide iterators that are powerful enough to accomplish the same thing.