我得到 cannot use map[string]MyType literal (type map[string]MyType) as type map[string]IterableWithID in argument to MapToList
使用下面的代码,我如何传递一个具体映射类型到需要接口(interface)类型的方法?
最佳答案
Go 的接口(interface)约定与 Java 中的接口(interface)约定不太一样(而且设计者显然不太喜欢 getter 和 setter 的想法 :-/)。所以你有两个核心问题:
- map[string]Foo 与 map[string]Bar 不一样,即使 Bar 实现了 Foo,所以你必须把它分解一下(事先使用 make(),然后在单个赋值中赋值) .
- 接口(interface)方法是按值调用的,没有指针,所以你真的需要在你的调用者中执行 foo = foo.Method(bar) 或者真的很高兴指针来实现这样的事情。
你可以做什么来或多或少地模拟你想要的东西:
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
最终的 value= 处理该方法获取值对象的新副本这一事实,因此您的方法不会触及原始副本(更改将完全消失)。
更新了 the Go Playground 上的代码
...但这并不是特别地道的 Go——他们真的希望你只引用结构成员而不是在接口(interface)中使用 Java 风格的修改器(尽管说实话我不太热衷于那个小细节——修改器是 supes方便进行验证)。
关于go - 将 map[string]SpecificType 与 map[string]SomeInterface 方法一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39402443/