Last active
December 25, 2023 21:03
-
-
Save flaviocopes/bed52cc2ac407137b3931bc864b4e31b to your computer and use it in GitHub Desktop.
Go: sort a Map by key #golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | |
//... | |
} |
@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
@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.