What would you do if you need a hash displayed in a fixed order?

Technology CommunityCategory: GolangWhat would you do if you need a hash displayed in a fixed order?
VietMX Staff asked 3 years ago
Problem

You would need to sort that hash’s keys.

fruits := map[string]int{
	"oranges": 100,
	"apples":  200,
	"bananas": 300,
}

// Put the keys in a slice and sort it.
var keys []string
for key := range fruits {
	keys = append(keys, key)
}
sort.Strings(keys)

// Display keys according to the sorted slice.
for _, key := range keys {
	fmt.Printf("%s:%v\n", key, fruits[key])
}
// Output:
// apples:200
// bananas:300
// oranges:100
This is open-ended question. Reference to your experience to provide a relevant answer.