find the range of all values in a map in go

To find the range of all values in a map in Go, you can use a combination of range loop and a couple of helper functions. Here is an example:

main.go
func findRange(m map[string]int) (int, int) {
    var min, max int
    for _, value := range m {
        if value < min || min == 0 {
            min = value
        }
        if value > max {
            max = value
        }
    }
    return min, max
}
255 chars
13 lines

In this function, we use the range loop to iterate through all the values in the map. For each value, we check if it is less than the current minimum or greater than the current maximum. If either of these conditions is true, we update the minimum and maximum values accordingly.

To use this function, simply pass your map as an argument and capture the return values:

main.go
myMap := map[string]int{"foo": 10, "bar": 20, "baz": 5}
min, max := findRange(myMap)
fmt.Printf("Range: %d-%d\n", min, max)
124 chars
4 lines

This will output: Range: 5-20.

related categories

gistlibby LogSnag