这里是初学者,我正在尝试创建一个通用例程来从 map 中提取值,我现在有这个:
func getValues(m map[interface{}]interface{}) []interface{} {
v := make([]interface{}, 0, len(m))
for _, value := range m {
v = append(v, value)
}
return v
}
我这样调用它:
nearby := make(map[string]Nearby)
values := getValues(nearby)
但是我得到这个错误:
cannot use nearby (type map[string]Nearby) as type map[interface {}]interface {} in argument to getValues
最佳答案
通常最好只编写特定于类型的代码。不过,要回答您的问题,请使用 reflect包裹:
func getValues(m interface{}) []interface{} {
v := reflect.ValueOf(m)
result := make([]interface{}, 0, v.Len())
for _, k := range v.MapKeys() {
result = append(result, v.MapIndex(k).Interface())
}
return result
}
关于go - 创建通用函数以从 map 中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52960147/