MMTTMM
在 Go 中,编写一个简单的函数。例如,package mainimport "fmt"func main() { items := map[string]int{ "one": 1, "two": 2, "three": 3, } keys := func(m map[string]int) []string { mk := make([]string, 0, len(m)) for k := range m { mk = append(mk, k) } return mk }(items) fmt.Printf("%d %q\n", len(keys), keys)}游乐场:https://play.golang.org/p/B0kOxAGbQCZ输出:3 ["three" "one" "two"]对于排序键,package mainimport ( "fmt" "sort")func main() { items := map[string]int{ "one": 1, "two": 2, "three": 3, } keys := func(m map[string]int) []string { mk := make([]string, 0, len(m)) for k := range m { mk = append(mk, k) } sort.Strings(mk) return mk }(items) fmt.Printf("%d %q\n", len(keys), keys)}游乐场:https://play.golang.org/p/IQLx7gjGk8j输出:3 ["one" "three" "two"]