Wanted to try generics and immediately struck the wall
I have following code that works ok , but when I want to extend to concrete type it fails.
Let code speak for itself
// general typed slice
type TSlice[T any] []T
func NewSlice[T any]() TSlice[T] {
ts := make([]T, 0)
return ts
}
func (s TSlice[T]) Length() int {
return len(s)
}
/// Float Slice
type FloatSlice TSlice[float64]
func NewFloatSlice() FloatSlice {
ts := NewSlice[float64]()
return FloatSlice(ts)
}
func (s FloatSlice) SomeSpecialFloatFunc() {
fmt.Println("special")
}
//// test
func Test_Slice(t *testing.T) {
f64Sl := NewSlice[float64]()
// OK
f64Sl.Push(2.1)
assert.Equal(t, 1, f64Sl.Length()) //OK
// I can slince
assert.Equal(t, 2.1, f64Sl[0]) //OK
floatSlice := NewFloatSlice()
floatSlice.SomeSpecialFloatFunc() //OK
//cant slice
floatSlice[0]
// ERROR Here no access to Push function
floatSlice.Push(2.1) //error floatSlice.Push undefined (type FloatSlice has no field or method Push)
}
I want to be able to “extend” base TSlice with concrete methods for those types , here is only a float64 example
Main probem is that FloatSlice does not “inherit” functions from base TSlice
Is there a solution for this or other way to handle it
Where Base can have common functions like Lenth() AtIndex() Append() etc , but extend from there when needed