【问题标题】:What's the best way to pass parameters to a function without tightly coupling with parameter type?在不与参数类型紧密耦合的情况下将参数传递给函数的最佳方法是什么?
【发布时间】:2019-07-12 16:11:02
【问题描述】:

我有两个结构体,每个结构体都有整数字段 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)
}

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

预期:我需要借助单个函数来解决用例。

【问题讨论】:

  • sum(a, b int64) int64
  • 函数func sum(details struct{ a, b int64 }) int64 { return details.a + details.b }适用于问题中的类型。
  • 接口是为不同类型定义共同行为的常规方式。我假设您的实际用例比您的示例更复杂,但对于示例,您可以定义获取 a 和 b 值的方法并定义包含这些方法的接口,然后编写您的 sum 函数取接口类型。
  • @CeriseLimón 该方法适用于较小的结构,但具有更大的功能和结构中的更多数据成员,那会不会很乱?
  • @mouryavenkat:是的,这种方法对于具有大量成员的结构来说不是一个好方法。就像我说的,这是问题中类型的解决方案。

标签: go interface reusability


【解决方案1】:

这是接口的经典用法。

// 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))
}

Playground

【讨论】:

    猜你喜欢
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多