当前位置: > > > > 在不与参数类型紧密耦合的情况下将参数传递给函数的最佳方法是什么?
在不与参数类型紧密耦合的情况下将参数传递给函数的最佳方法是什么?
来源:stackoverflow
2024-04-23 17:12:34
0浏览
收藏
从现在开始,努力学习吧!本文《在不与参数类型紧密耦合的情况下将参数传递给函数的最佳方法是什么?》主要讲解了等等相关知识点,我会在米云中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!
问题内容
我有两个结构,每个结构都有整数字段 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的相关知识,也可关注米云公众号。
