go - 如何在不知道值类型的情况下访问 map 的键?

标签 go types casting

如果我在接口(interface)变量中有一个映射并想访问一个键,但不知道映射的值是什么类型,我该如何访问该键?

Here是 go playground 上的一个例子

为了解决我的问题,我需要弄清楚如何让主函数无错误地运行。

最佳答案

使用 reflect对任意 map 类型进行操作的包:

func GetMapKey(reference interface{}, key string) (interface{}, error) {
    m := reflect.ValueOf(reference)
    if m.Kind() != reflect.Map {
        return nil, errors.New("not a map")
    }
    v := m.MapIndex(reflect.ValueOf(key))
    if !v.IsValid() {
        return nil, errors.New("The " + key + " key was not present in the map")
    }
    return v.Interface(), nil
}

关于go - 如何在不知道值类型的情况下访问 map 的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48916313/

相关文章:

pdf - 使用 golang 提供 pdf

java - 当notifyAll()调用时,恢复顺序是什么?

haskell - 在类型同义词声明中循环

Java 转换错误?

sql - 无法在 presto 中将 '' 转换为 bigint

go - 未定义 : function (declared in another package)

android-studio - Gomobile 工具链已过时,仅适用于 Android Studio

html - 如何转换HTML标签中的转义字符?

types - 表示多边形链的最佳方式

java - 将泛型集合转换为数组