go - 如何将相同的方法应用于 Go 中的不同类型?

标签 go

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 }

现在您可以在 type1type2 实例或您需要此功能的任何其他类型中调用 Do()

编辑:根据您的评论,您可以重新定义一些等效类型,例如遵循所需协议(protocol)的 t1t2(具有一个 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.Type1yetanother.Type2 不是您定义的。但是你可以用 t1t2 做任何逻辑要求 - 就公共(public)成员而言,或者如果你愿意弄乱那个反射的东西:)

关于go - 如何将相同的方法应用于 Go 中的不同类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42352873/

相关文章:

go - map 实现 - Lookup() 和 Insert() 中的代码异味

json - 如何从json中获取相同的hash

pointers - 为什么 golang 中的字符串指针在范围循环中的行为违反直觉?

在 Go 中对共享的嵌套结构属性进行排序

go - 在 Go 中检测有符号整数溢出

go - 使用 os.Stat 与仅 os.MkdirAll 检查

go - 从 Mutating Admission Controller 中创建一个新的 Kubernetes 对象

go - 使用服务帐户从 Google REST API 获取数据

ssl - 带有 Apache2 SNI/主机名错误的 Golang ReverseProxy

go - 函数 ioutil.WriteFile 的参数中的数字