dongmengan8620 2016-09-09 01:20
浏览 151

将map [string] SpecificType与map [string] SomeInterface方法一起使用

I get cannot use map[string]MyType literal (type map[string]MyType) as type map[string]IterableWithID in argument to MapToList with the code below, how do I pass in a concrete map type to method that expects a interface type?

https://play.golang.org/p/G7VzMwrRRw

  • 写回答

2条回答 默认 最新

  • doujing8435 2016-09-09 02:40
    关注

    Go's interface convention doesn't quite work the same way as in, say, Java (and the designers apparently didn't like the idea of getters and setters very much :-/ ). So you've got two core problems:

    1. A map[string]Foo is not the same as a map[string]Bar, even if Bar implements Foo, so you have to break it out a bit (use make() beforehand, then assign in a single assignment).
    2. Interface methods are called by value with no pointers, so you really need to do foo = foo.Method(bar) in your callers or get really pointer-happy to implement something like this.

    What you can do to more-or-less simulate what you want:

    type IterableWithID interface {
        SetID(id string) IterableWithID     // use as foo = foo.SetID(bar)
    }
    
    func (t MyType) SetID(id string) IterableWithID {
        t.ID = id
        return t
    }
    
    ...and to deal with the typing problem
    
    t := make(map[string]IterableWithID)
    t["foo"] = MyType{}
    MapToList(t)              // This is a map[string]IterableWithID, so compiler's happy. 
    
    ...and finally...
    
    value = value.SetID(key)  // We set back the copy of the value we mutated
    

    The final value= deals with the fact that the method gets a fresh copy of the value object, so the original would be untouched by your method (the change would simply vanish).

    Updated code on the Go Playground

    ...but it's not particularly idiomatic Go--they really want you to just reference struct members rather than use Java-style mutators in interfaces (though TBH I'm not so keen on that little detail--mutators are supes handy to do validation).

    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致