我试图编写一个通用函数来获取地图的键,如下所示:
func MapKeys(theMap map[interface{}]interface{}) ([]interface{},error) {
if theMap == nil {
return nil,errors.New("MapKeys arg is nil")
}
var keys = make([]interface{}, len(theMap), len(theMap))
i := 0
for idx,_ := range theMap {
keys[i] = idx
i++
}
return keys, nil
}
A)有更好的方法吗?和B)调用此函数时,如何将原始地图类型转换为map [interface {}] interface {}?
答案 0 :(得分:1)
您无法将现有地图投射到map[interface{}]interface{}
。你必须使用反射:
func MapKeys(theMap interface{}) ([]interface{}, error) {
if theMap == nil {
return nil,errors.New("MapKeys arg is nil")
}
v := reflect.ValueOf(theMap) // v is now a reflect.Value type
if v.Kind() != reflect.Map {
return nil, errors.New("Argument is not a map")
}
var keys = make([]interface{}, v.Len(), v.Len())
for i, key := range v.MapKeys() {
keys[i] = key.Interface() // key is also a reflect.Value, key.Interface()
// converts it back into an interface
}
return keys, nil
}