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

标签 go

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

相关文章:

go - 在 Go 中通过 Godoc 记录私有(private)结构上的公共(public)方法

go - 如何将数据添加到在 Go 中作为参数的接口(interface)?

go - 无法从 IDP 创建 SAML 响应

ssl - 如何访问我的 TLS/HTTPS key 以启动 ListenAndServeTLS?

go - 无需等待流缓冲区刷新即可将数据上传到表

javascript - zserge/lorca ui.Eval 没有返回值

go - 从 golang 中的模板创建 yaml 文件

http - panic : runtime error: invalid memory address or nil pointer dereference with bigger data

go - GO 中的包/函数中毒

reflection - golang - 如何访问结构的内部结构(反射?)