[英]How to apply same method to different types in Go?
如何在不重复代码的情况下将相同方法应用于不同类型? 我有type1和type2,并且想应用方法Do()
type type1 struct { }
type type2 struct { }
我必须重复代码,请参见下文。 Go具有静态类型,因此必须在编译时确定类型。
func (p type1) Do() { }
func (p type2) Do() { }
这很好..但我不喜欢重复代码
type1.Do()
type2.Do()
目前尚不清楚逻辑的处理方式,但是Go中的一种常见模式是将共享功能封装在另一种struct类型中,然后将其嵌入您的类型中:
type sharedFunctionality struct{}
func (*sharedFunctionality) Do() {}
type type1 struct{ sharedFunctionality }
type type2 struct{ sharedFunctionality }
现在,您可以在type1
和type2
实例或需要此功能的任何其他类型中调用Do()
。
编辑:根据您的评论,您可以重新定义遵循期望协议的某些等效类型,例如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
的逻辑要求执行任何操作-就公共成员而言,或者您是否愿意破坏该反射对象:)
Go中最接近的一种类型是嵌入另一种类型。
type Type1 struct {}
func (t *Type1) Do() {
// ...
}
type Type2 struct {
*Type1
}
唯一的限制是您的Do()
函数将只能访问Type1的字段。
我认为,您可以在此处使用界面。 例:
package main
import "fmt"
type testInterface interface {
Do()
}
type type1 struct{}
type type2 struct{}
func (t type1) Do() {
fmt.Println("Do type 1")
}
func (t type2) Do() {
fmt.Println("Do type 2")
}
func TestFunc(t testInterface) {
t.Do()
}
func main() {
var a type1
var b type2
TestFunc(a)
TestFunc(b)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.