如何使用反射在Go语言中获取map接口的值?

12

我正在尝试在Go语言中获取接口映射的值。

val := reflect.ValueOf(Schema)
fmt.Println("VALUE = ", val)
fmt.Println("KIND = ", val.Kind())
if val.Kind() == reflect.Map {
    fmt.Println("len = ", val.Len())
    for key, element := range val.MapKeys() {
        fmt.Println(key, element) // how to get the value?
    }
}

这会输出:

VALUE =  map[testString:foobar testInt:1 testBoolean:true testNumber:1 testDateTime:2017-10-06 08:15:30 +0100 +0100]
KIND =  map
len =  5
0 testString
1 testInt
2 testBoolean
3 testNumber
4 testDateTime

我的问题
如何获取map项的类型和值?


fmt.Println(val.MapIndex(element)) //获取值 - Uvelichitel
1个回答

18
你很接近了,可以使用从MapKeys返回的键,然后使用MapIndex获取映射键的值。以下是我使用switch语句将接口的值转换为正确类型的示例。
package main

import (
    "fmt"
    "reflect"
)

func main() {
    Schema := map[string]interface{}{}
    Schema["int"] = 10
    Schema["string"] = "this is a string"
    Schema["bool"] = false

    val := reflect.ValueOf(Schema)
    fmt.Println("VALUE = ", val)
    fmt.Println("KIND = ", val.Kind())

    if val.Kind() == reflect.Map {
        for _, e := range val.MapKeys() {
            v := val.MapIndex(e)
            switch t := v.Interface().(type) {
            case int:
                fmt.Println(e, t)
            case string:
                fmt.Println(e, t)
            case bool:
                fmt.Println(e, t)
            default:
                fmt.Println("not found")

            }
        }
    }
}

程序输出:

VALUE =  map[int:10 string:this is a string bool:false]
KIND =  map
int 10
string this is a string
bool false

哦,是的,这就是它。谢谢! - Bob van Luijt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接