【发布时间】:2014-11-24 06:52:14
【问题描述】:
我一直在阅读the go-lang interface doc;但是我仍然不清楚是否有可能实现我想要的目标
type A struct {
ID SomeSpecialType
}
type B struct {
ID SomeSpecialType
}
func (a A) IDHexString() string {
return a.ID.Hex()
}
func (b B) IDHexString() string {
return b.ID.Hex()
}
这会很好用;但是我更喜欢一些惯用的方法来将通用方法应用于两种类型并且只定义一次。类似的东西:
type A struct {
ID SomeSpecialType
}
type B struct {
ID SomeSpecialType
}
func (SPECIFY_TYPE_A_AND_B_HERE) IDHexString() string {
return A_or_B.ID.Hex()
}
【问题讨论】:
-
你不能,但你可以使用嵌入,因此在任何结构中嵌入
mypkg.ID都会给它IDHexString方法。遗憾的是我没有时间写详细信息,但golang.org/doc/effective_go.html#embedding 可能会有所帮助。
标签: go go-interface