vendredi 16 octobre 2015

How to make a map pointer using reflect?

I need to pass a pointer to a map to another function using the reflect package. Think of encodin/json.Unmarshal which accepts only pointers. Below is some code of what I need to do using reflection:

  m := make(map[string]MyType)
  x := decode(&m)

So far I have the following:

  var typ MyType 
  m := reflect.MakeMap(reflect.MapOf(reflect.TypeOf(""),  reflect.TypeOf(typ))
  x := decode(m.Interface())

The issue with this code is that it's making a map of map[string]MyType but there is no way I can create a pointer for it. If I try to make the pointer [2] directly it panics with reflect.MakeMap of non-map type

[2] reflect.MakeMap(reflect.PtrTo(reflect.MapOf(reflect.TypeOf("")), reflect.TypeOf(typ))





Aucun commentaire:

Enregistrer un commentaire