优惠全部云服务器首月 8 折,优惠码 CLOUD去领取

在不与参数类型紧密耦合的情况下将参数传递给函数的最佳方法是什么?

· 阅读约 3 分钟

问题内容

我有两个结构,每个结构都有整数字段 a、b。现在我想编写一个名为 sum 的函数,其结果为 a+b

type Type1 struct {
    a int64
    b int64
}

type Type2 struct {
    a int64
    b int64
}

func sum(details Type1) int64 {
    return details.a + details.b
}

func sum2(details Type2) int64 {
    return details.a + details.b
}

func main() {
    type1Obj: = Type1 {}
    type2Obj: = Type2 {}
    sum(type1Obj)
    sum2(type2Obj)
}

实际:我正在为相同的行为创建两个函数,只是因为类型。

预期:我需要在单个函数的帮助下解决用例。

解决方案

这是界面的经典用法。

// there is some interface that expresses the behaviors you need
type summable interface {
    a() int64
    b() int64
}

// and it can be summed
func sum(s summable) int64 {
    return s.a() + s.b()
}

然后你可以将各种类型符合summable:

type type1 struct {
    a int64
    b int64
}

// type1 conforms to summable
func (t type1) a() int64 { 
    return t.a 
}

func (t type1) b() int64 {
    return t.b
}

type type2 struct {
    a int64
    b int64
}

// and so does type2
func (t type2) a() int64 { 
    return t.a 
}

func (t type2) b() int64 {
    return t.b
}

然后您可以对任何 summable 类型求和:

func main() {
    type1Obj := Type1 {}
    type2Obj := Type2 {}
    println(sum(type1Obj))
    println(sum(type2Obj))
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持!更多关于Golang的相关知识,也可关注公众号。

相关文章

更多「网站和优化」文章服务器使用指南