Go 什么';将参数传递给函数而不与参数类型紧密耦合的最佳方法是什么?
我有两个结构,每个结构都有整数字段a,b。现在我想写一个名为sum的函数,结果是a+bGo 什么';将参数传递给函数而不与参数类型紧密耦合的最佳方法是什么?,go,interface,reusability,Go,Interface,Reusability,我有两个结构,每个结构都有整数字段a,b。现在我想写一个名为sum的函数,结果是a+b 类型1结构{ int64 b int64 } 类型2结构{ int64 b int64 } func sum(详细信息类型1)int64{ 返回详细信息。a+详细信息。b } func sum2(详细信息类型2)int64{ 返回详细信息。a+详细信息。b } func main(){ type1Obj:=Type1{} type2Obj:=Type2{} 金额(类型1OBJ) sum2(2OBJ型) }
类型1结构{
int64
b int64
}
类型2结构{
int64
b int64
}
func sum(详细信息类型1)int64{
返回详细信息。a+详细信息。b
}
func sum2(详细信息类型2)int64{
返回详细信息。a+详细信息。b
}
func main(){
type1Obj:=Type1{}
type2Obj:=Type2{}
金额(类型1OBJ)
sum2(2OBJ型)
}
实际:我正在为相同的行为创建两个函数,只是因为类型不同
预期:我需要借助单个函数解决用例。这是接口的经典用法
// 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
}
然后您可以对任何可求和类型求和:
func main() {
type1Obj := Type1 {}
type2Obj := Type2 {}
println(sum(type1Obj))
println(sum(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:是的,这种方法对于成员众多的结构来说不是一种好方法。就像我说的,这是问题类型的解决方案。