Question:

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

Answer:

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

Keywords:

© 2017 QuizBucket.org