Skip to content

Instantly share code, notes, and snippets.

@flaviocopes
Last active December 25, 2023 21:03
Show Gist options
  • Save flaviocopes/bed52cc2ac407137b3931bc864b4e31b to your computer and use it in GitHub Desktop.
Save flaviocopes/bed52cc2ac407137b3931bc864b4e31b to your computer and use it in GitHub Desktop.
Go: sort a Map by key #golang
import "sort"
ages := map[string]int{
"a": 1,
"c": 3,
"d": 4,
"b": 2,
}
names := make([]string, 0, len(ages))
for name := range ages {
names = append(names, name)
}
sort.Strings(names) //sort by key
for _, name := range names {
//...
}
@ernierasta
Copy link

ernierasta commented Feb 10, 2022

@mellorn-anz I completely agree with you, I was just saying how it is and why it is like that. But while there are workarounds (like: https://github.com/elliotchance/orderedmap) I would also love to see native ordered map in go.

@wvh
Copy link

wvh commented Dec 2, 2023

@zmf I am wondering what's the reason that the iteration of the maps is by design random.

I'm guessing it has something to do with garbage collection and the hash backing store scaling up or down. Originally, if I remember correctly, insertion order was mostly predictable, but not always, and because it wasn't guaranteed, the Go devs decided to make sure people wouldn't rely on the insertion order being stable.

I think it was changed again fairly recently to make things like testing easier.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment