I have an interface Cells
with several methods
type Cells interface{
Len() int
//....
}
Concrete implementations of this are StrCells
, IntCells
, FloatCells
and BoolCells
, all of which have the above methods implemented.
E.g.:
type StrCells []string
func (sC StrCells) Len() int {return len(sC)}
//...
type IntCells []int
func (iC IntCells) Len() int {return len(iC)}
//...
//....
For two of the concrete types - IntCells
and FloatCells
- I want to implement specific functions only applicable to those types.
I create a new interface NumCells
which embedds Cells
type NumCells interface{
Cells
Add(NumCells) interface{} // should return either IntCells or FloatCells
}
Here is my implementation of Add()
for IntCells:
func (iC IntCells) Add(nC NumCells) interface{} {
if iC.Len() != nC.Len() {
// do stuff
}
switch nC.(type) {
case IntCells:
res := make(IntCells, iC.Len())
for i, v := range iC {
res[i] = v + nC.(IntCells)[i]
}
return res
case FloatCells:
res := make(FloatCells, iC.Len())
for i, v := range iC {
res[i] = float64(v) + nC.(FloatCells)[i]
}
return res
default:
// to come
return nil
}
}
Here is my question / problem
The function works, however, I actually want the function to return NumCells
(i.e. either IntCells or FloatCells) so I could do method chaining like this
a := columns.IntCells(1, 2, 4, 2)
b := columns.IntCells{2, 3, 5, 3}
c := columns.FloatCells{3.1, 2, 2.4, 3.2}
d := a.Add(b).Add(c)
This is not possible if Add()
returns an interface{}
. However, I am not able to make the function work otherwise.