Go 中如何在不重复代码的情况下将相同的方法应用于不同的类型?我有 type1 和 type2 并且想应用方法 Do()
type type1 struct { }
type type2 struct { }
我必须重复代码,见下文。 Go 具有静态类型,因此必须在编译时确定类型。
func (p type1) Do() { }
func (p type2) Do() { }
这很好..但我不喜欢重复代码
type1.Do()
type2.Do()
最佳答案
目前尚不清楚这里的逻辑是如何进行的,但 Go 中的一种常见模式是将共享功能封装在另一种结构类型中,然后将其嵌入到您的类型中:
type sharedFunctionality struct{}
func (*sharedFunctionality) Do() {}
type type1 struct{ sharedFunctionality }
type type2 struct{ sharedFunctionality }
现在您可以在 type1
和 type2
实例或您需要此功能的任何其他类型中调用 Do()
。
编辑:根据您的评论,您可以重新定义一些等效类型,例如遵循所需协议(protocol)的 t1
和 t2
(具有一个 Do()
方法)像这样:
func main() {
var j job
j = new(t1)
j.Do()
j = new(t2)
j.Do()
}
type job interface {
Do()
}
type t1 another.Type1
func (*t1) Do() {}
type t2 yetanother.Type2
func (*t2) Do() {}
此处类型 another.Type1
和 yetanother.Type2
不是您定义的。但是你可以用 t1
和 t2
做任何逻辑要求 - 就公共(public)成员而言,或者如果你愿意弄乱那个反射的东西:)
关于go - 如何将相同的方法应用于 Go 中的不同类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42352873/