douxian1923 2018-07-03 18:43
浏览 78
已采纳

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

I'm struggling to get the value of an interface map in 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?
    }
}

This outputs:

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

My question:
How can I get the type and value of the map items?

  • 写回答

1条回答 默认 最新

  • duanboxue3422 2018-07-03 19:19
    关注

    You were close, you can use the key returned form MapKeys and then use MapIndex to get the value of the map key. Below I use a switch statement to convert the value of the interface to the correct type.

    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")
    
                }
            }
        }
    }
    

    Program Output:

    VALUE =  map[int:10 string:this is a string bool:false]
    KIND =  map
    int 10
    string this is a string
    bool false
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测