Suppose I have a map[string]int
, and I want the key with the shortest length (in bytes). If I don't know any particular element that the map contains, how do I get a sample of it so I can do
var shortest string
for key, _ := range myMap {
if len(key) < len(shortest) {
shortest = key
}
}
You can use a for
loop and break out of it immediately to sample just one element.
var shortest string
for key, _ := range myMap {
shortest = key
break
}
for key, _ := range myMap {
if len(key) < len(shortest) {
shortest = key
}
}
Ugly, but it works.
You could iterate over the map, adding the elements to a slice. Then sort the slice:
var keys []string
for k := range myMap {
keys = append(keys, k)
}
sort.Strings(keys) // keys[0] is the shorted
You should first define two variables shortestLength
and shortest
, they will record shortest length you found until now, and corresponding key, respectively. And then start iterating over the map.
Here, the trick is to initialise shortestLength
variable with a value, which will be over-written in the first pass. The benefit is that, you don't have to write any extra code and allocate extra memory to sort the keys, and find the shortest one.
Complete code is as following:
if len(myMap) == 0 {
// Empty map
}
// Will be over-written in first iteration
shortestLength := maths.MaxInt32
shortest := ""
for key, _ := range myMap {
keyLength := len(key)
if keyLength <= shortestLength {
shortest = key
shortestLength = keyLength
}
}
The variable shortestLength
will be over-written with the length of first element in the first iteration of our for loop. And at the end of the loop will contain the length of shortest key. And shortest
will contain the key itself.