find the smallest value in a map in go

To find the smallest value in a map in Go, you can iterate through the map using a for loop and keep track of the minimum value seen so far. Here's an example implementation:

main.go
func findMinValue(m map[string]int) int {
    minValue := int(^uint(0) >> 1) // initialize with the highest possible int value

    for _, value := range m {
        if value < minValue {
            minValue = value
        }
    }

    return minValue
}
256 chars
12 lines

In this implementation, we initialize the minValue variable with the highest possible integer value (we assume that our map contains only positive integers). Then, we loop through all the values in the map using the range keyword and update minValue if we find a smaller value.

To use this function, you can simply call it with your map as an argument:

main.go
myMap := map[string]int{"a": 3, "b": 2, "c": 5}
minValue := findMinValue(myMap)
fmt.Println(minValue) // output: 2
115 chars
4 lines

gistlibby LogSnag