在 Go 1.18 或更高版本中使用泛型:
// Keys returns the keys from in map m.
func keys[M ~map[K]V, K comparable, V any](m M) []K {
result := make([]K, 0, len(m))
for k := range m {
result = append(result, k)
}
return result
}
像这样使用它:
r := keys(map[string]string{"Foo": "Bar", "Quux": "Baz"})
// r is a []string
在 1.18 之前的 Go 版本中,使用 reflect 包从任意映射类型中提取键:
// Keys stores the keys from m to the slice pointed to by pkeys.
// The slice element type must be the same as the map key type.
func keys(m interface{}, pkeys interface{}) {
result := reflect.ValueOf(pkeys).Elem()
result.SetLen(0)
result.Set(reflect.Append(result, reflect.ValueOf(m).MapKeys()...))
}
像这样使用它:
var result []string
keys(map[string]string{"Foo": "Bar", "Quux": "Baz"}, &result)
fmt.Println(result) // prints [Foo Quux]
以下是为特定键类型编写函数的方法。在本例中,密钥类型为int:
// Keys returns the keys for for map m with int keys.
func keys(m interface{}) []int {
mv := reflect.ValueOf(m)
result := make([]int, mv.Len())
for i, key := range mv.MapKeys() {
result[i] = key.Interface().(int)
}
return result
}
像这样使用它:
result := keys(map[int]string{1: "Bar", 2: "Baz"})
fmt.Println(result) // prints [1 2]
See all of the examples in action on the Go playground.