如何在Go中通过反射获取地图界面的值?

Bob*_*ijt 4 go

我正在努力获取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?
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

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

jma*_*ney 5

亲密无间,您可以使用键返回的表单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")

            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

程序输出:

VALUE =  map[int:10 string:this is a string bool:false]
KIND =  map
int 10
string this is a string
bool false
Run Code Online (Sandbox Code Playgroud)