What would you do if you need a hash displayed in a fixed order?
What would you do if you need a hash displayed in a fixed order?
To display a hash in a fixed order in Go, you would need to sort the keys of the hash (map) first, as Go maps do not maintain any inherent order of their keys. Here's how you can achieve this:
sort
package to sort the slice of keys.Here is an example implementation in Go:
package main
import (
"fmt"
"sort"
)
func main() {
fruits := map[string]int{
"oranges": 5,
"apples": 3,
"bananas": 2,
}
// Extract keys to a slice
keys := make([]string, 0, len(fruits))
for k := range fruits {
keys = append(keys, k)
}
// Sort keys
sort.Strings(keys)
// Display map in sorted order of keys
for _, k := range keys {
fmt.Printf("%s: %d\n", k, fruits[k])
}
}
In this example:
fruits
is created with string keys and integer values.This method ensures that the hash is displayed in a predictable order, which can be crucial for tasks like unit testing, where consistent outputs are necessary[19].
Citati...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào