I'm working on a little side projects, and I want to have a slice in Go, with any amount of elements with a different type parameter.
Is something like that possible?
I've tried the following:
func main() {
fCallOne := functionCall[bool]{
returnValue: false,
}
fCallTwo := functionCall[int]{
returnValue: 0,
}
fCalls := make([]functionCall[any], 10)
fCalls = append(fCalls, fCallOne)
}
type functionCall[T any] struct {
returnValue T
}
But this doesn't work. I would like to be able to do something like:
Store an amount of elements in a slice (all sharing the same API). Retrieve the value of a given index in the slice (without any type casting).
What would be the best approach to pull something like this off?
Currently, I'm down to the following but this doesn't work either:
func main() {
container := make([]tuple[any], 0)
elem := T1[bool]{
V1: false,
}
container = append(container, elem)
}
type tuple[T any] interface {
getValue() T
}
// T1 is a tuple type holding 1 generic values.
type T1[Ty1 any] struct {
V1 Ty1
}
func (t T1[Ty1]) getValue() Ty1 {
return t.V1
}