我只是想在Golang中编写一个像jsoncpp这样使用起来很愉快的JSON阅读器包装。是否可以在Golang中创建具有动态类型的地图?
例如:
package main
import "reflect"
func main() {
i := 1 // type int
myType := reflect.TypeOf(i) // type Type
a := make(map[string]myType) // make a map of Type
a["KEY"] = i // Assign an int to the map
}
我在做梦吗?
有人会说“这就是Go具有这种类型的原因interface{}
”,但是,我不想做这样的事情:
myMap["key"].(map[string]string)["subKey1"].([]map[string]interface)["subKey2"].(int)
我想做这样的事情:
myMap["key"]["subKey1"][0]["subKey2"]
也许一个好的灵魂以前已经编码过这样的包装器,但是我在任何地方都找不到
这是如何创建动态地图的示例。
package main
import (
"reflect"
"fmt"
)
func main() {
var key = "key1"
var value = 123
var keyType = reflect.TypeOf(key)
var valueType = reflect.TypeOf(value)
var aMapType = reflect.MapOf(keyType, valueType)
aMap := reflect.MakeMapWithSize(aMapType, 0)
aMap.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(value))
fmt.Printf("%T: %v\n", aMap.Interface(), aMap.Interface())
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句