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.
It works if you define your NumCells
interface this way:
type NumCells interface{
Cells
Add(NumCells) NumCells // returns either IntCells or FloatCells
}
You then need both IntCells
and FloatCells
to implement Add
and return one of those types.
Here's a working playground, using method chaining and printing the result:
https://play.golang.org/p/W7DzcB4A3NH
As stated in the comments, when using interfaces one usually wants to make each type agnostic of the rest of the implementations and just use the interface without type switches.
One way to avoid those type switches in the implementations of Add
might be to add another method in the NumCells
to return a particular position as a float64
.
type NumCells interface{
Cells
Add(NumCells) NumCells // returns either IntCells or FloatCells
GetCell(index int) float64
}
So that then you can get the value without needing to assert the particular type.
Since IntCells
cannot accommodate float64
values, it'd still need to create a FloatCells
to return it, if we want to avoid IntCells
doing that we'd need to abstract the creation of the objects somehow, using a factory pattern or similar.