douye7033 2015-10-16 21:31
浏览 29
已采纳

如何使用反射制作地图指针?

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

  myTyp := &MyType{}
  json.Unmarshal(jsonPayload1, myTyp)
  m := make(map[string]*MyType)
  m["someKey"] = myTyp
  // Dump it again to Unmarshal. It will overwrite it only if 
  // there is a `someKey` key.
  x := json.Unmarshal(jsonPayload2, &m)

So far I have the following:

  ....
  m := reflect.MakeMap(reflect.MapOf(reflect.TypeOf(""), reflect.TypeOf(typ))
  x := json.Unmarshal(jsonPayload2, 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.

Why the map must be allocated:

I need the map allocated so that I can set myTyp on a specific key. myTyp is decoded using multiple decoding sources so I don't know what fields were decoded with each source but I know that Unmarshal overwrites only keys that match the json content/keys so it's safe to use the same variable to multiple Unmarshal functions.

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

  • 写回答

1条回答 默认 最新

  • duanbing8817 2015-10-16 21:50
    关注

    For a function like json.Unamrshal, you don't need the map, you only need the correct type pointer, which you can make with reflect.New. The json package will allocate the map as needed.

    m := reflect.New(reflect.MapOf(reflect.TypeOf(""), reflect.TypeOf(typ)))
    

    If you need to allocate the map, use the Set method to assign it to the pointer.

    http://play.golang.org/p/hnOhh8242i

    mapType := reflect.MapOf(reflect.TypeOf(""), reflect.TypeOf(typ))
    
    ptr := reflect.New(mapType)
    ptr.Elem().Set(reflect.MakeMap(mapType))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图