dongyuan1870 2017-01-11 11:01
浏览 21
已采纳

通过反射创建然后修改地图

I have a new type derived from map such:

type mapp map[string]interface{}

with a small function on it

func (c mapp) Set() error {
    // c is nil
    c["a"] = "b"
    return nil
}

type Setter interface {
  Set() error
}

func main() {
    var aa mapp
    out := reflect.ValueOf(&aa)
    s := out.Interface().(Setter)
    s.Set()
}

This code works on a struct, why this code fails when it comes to a type of a map?

Here's a playground: https://play.golang.org/p/Z1LFqb6kF7

Many thanks,

Asaf.

  • 写回答

1条回答 默认 最新

  • dpvmjk0479 2017-01-11 11:07
    关注

    Go maps (and slices) are created via make. The equivalent function in reflect is reflect.MakeMap

    out := reflect.ValueOf(&aa).Elem()
    out.Set(reflect.MakeMap(out.Type()))
    s := out.Interface().(Setter)
    s.Set()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部