find the smallest key in a map in go

To find the smallest key in a map in Go, you can loop through the keys and keep track of the minimum key found so far using the built-in math package. Here's an example code snippet:

main.go
import "math"

func findSmallestKey(m map[string]int) string {
    // initialize the minimum key to the largest possible value
    minKey := ""
    minValue := math.MaxInt32

    // loop through the keys of the map
    for key, value := range m {
        // if the current key is smaller than the minimum key found so far, update the minimum key
        if key < minKey {
            minKey = key
            minValue = value
        }
    }
    
    // return the smallest key found
    return minKey
}
504 chars
20 lines

You can then call this function with your map to get the smallest key:

main.go
m := map[string]int{"c": 3, "a": 1, "b": 2}
minKey := findSmallestKey(m)
fmt.Println(minKey) // prints "a"
107 chars
4 lines

related categories

gistlibby LogSnag