mardi 8 mai 2018

create a map in Go using reflection

I'm just playing around trying to write a JSON reader wrapper in Golang that is pleasant to use like jsoncpp. Is it possible to create a map with a dynamic type in Golang?

For instance:

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
}

Am I dreaming?

Some people would say "That's why Go have the type interface{}", however, I don't want be doing something like this:

myMap["key"].(map[string]string)["subKey1"].([]map[string]interface)["subKey2"].(int)

I want to do something like this:

myMap["key"]["subKey1"][0]["subKey2"]

Perhaps a good soul have already coded a wrapper like this before but I couldn't find it anywhere





Aucun commentaire:

Enregistrer un commentaire