gpt4 book ai didi

go - 创建通用函数以从 map 中提取值

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:30 25 4
gpt4 key购买 nike

这里是初学者,我正在尝试创建一个通用例程来从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com