Facing difficulty in extracting keys from a map in the same order present in the 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.

Thank you

Just create a slice and add the keys in a for/range loop. For example

package main
import "fmt"

func main() {
m := map[string]int{
	"rsc": 3711,
	"r":   2138,
	"gri": 1908,
	"adg": 912,
}

keys := make([]string, 0, len(m))
for k := range m {
	keys = append(keys, k)
}
fmt.Println(keys)
}

Not always getting the keys in the same order present in map

A map has no order. If you want this behaviour, you will have to implement your own type.

There are libraries that implement ordered maps. Example: