Since a plain 'string []keys
' does not meet the sort.Interface
(the compiler says 'missing Len() (int)'), there isn't much you can do to reduce that code (and even though attempting to use 'string []keys
' avoids using a StringVector, it adds a couple of lines to the code (for the declaration of an index variable and the incrementing of it).
So, unless there is an automatic way of converting from a map to a vector of the keys that I've not been able to divine from the documentation, what you have here is about as succinct as it gets.
To use the sort
package, the type must provide the sort.Interface
. You have to have a mechanism to access the data in the container type to access the elements by integer indexes, as well as the Len(), LessThan() and Swap() methods.
Code that fails to compile, and is in any case one line longer than the original:
package main
import "fmt"
import "sort"
func main() {
m := map[string]string{"b": "15", "z": "123123", "x": "sdf", "a": "12"}
var keys []string
var i int
for k, _ := range (m) {
keys[i] = k
i++
}
sort.Sort(&keys)
fmt.Printf("%v\n", keys)
}
The compilation error:
so-2038508-jl.go:14: *[]string is not sort.Interface
missing Len() (int)