我试过了
func Keys(m map[string]interface{}) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
return keys
}
但
cannot use m (type map[string]int) as type map[string]interface {} in argument to Keys
我知道golang不支持泛型,因此可以统一获取 key slice 吗?
最佳答案
使用reflect包从具有任意值类型的映射中获取字符串键:
func Keys(v interface{}) ([]string, error) {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Map {
return nil, errors.New("not a map")
}
t := rv.Type()
if t.Key().Kind() != reflect.String {
return nil, errors.New("not string key")
}
var result []string
for _, kv := range rv.MapKeys() {
result = append(result, kv.String())
}
return result, nil
}
playground example
关于go - 如何从golang的 map 中统一获取 key 片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39239561/