gpt4 book ai didi

go - 如何在 Go 中使用 reflect 获取 map 接口(interface)的值?

转载 作者:IT王子 更新时间:2023-10-29 01:01:16 25 4
gpt4 key购买 nike

我正在努力获取 Go 中接口(interface)映射的值。

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 项的类型和值?

最佳答案

你很接近,你可以使用从 MapKeys 返回的键,然后使用 MapIndex 来获取映射键的值。下面我使用switch语句将接口(interface)的值转换为正确的类型。

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

关于go - 如何在 Go 中使用 reflect 获取 map 接口(interface)的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51161150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com