Facing difficulty in extracting keys from a map in the same order present in a map

How to get the keys in the same order as stored in a map of type “map[string]interface{}”?
I’ve tried MapKeys() from reflect package and also tried extracting using a “for loop”, but couldn’t get keys in the same order as they are present in map.
Please do help me with this.

There is not order if keys in map, you need to choose a different data structure.

1 Like

Credit “The Go Workshop” - Packt
“When looping over a map, never rely on the order of the items
in it. Go doesn’t guarantee the order of items in a map. To make sure no one relies on
the order of the elements, Go purposely randomizes the order of them when you range
over a map. If you did need to loop over the elements of your map in a specific order,
you’d need to use an array or slice to assist you with that.”

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.