I have two structs each with integer fields a, b. Now I want to write a function called sum which results 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)
}
Actual : I am creating two functions for same behaviour, just because of type.
Expected : I need to solve the use case with help of single function.
This is a classic use of an interface.
// 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()
}
Then you can conform various types to 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
}
And then you can sum any Summable type:
func main() {
type1Obj := Type1 {}
type2Obj := Type2 {}
println(sum(type1Obj))
println(sum(type2Obj))
}