Hi All,
I'm just trying generics and bump into this.
# command-line-arguments
./main.go:21:12: m.x undefined (type T has no field or method x)
this is the source code
package main
import "fmt"
type A struct {
x int
}
type B struct {
x int
y int
}
type Model interface {
A | B
}
func Reduce[T Model](arr []T) int {
sum := 0
for _, m := range arr {
sum += m.x
}
return sum
}
func main() {
a := []A{
{x: 1},
{x: 2},
}
v := Reduce[A](a)
fmt.Printf("v = %+v\n", v)
}
It does work however if I take out (`y int`) out of B struct. meaning A & B has the same properties
I can imagine that this is very trivial example and can be solve not by using generic ( eg. with method dispatch by providing getter of X)
I'm trying to clean up existing source code using generics in similar situation. It's an ETL process with model that has a lot of attribute. Not looking forward to adding extra method on the struct.
Is there a better approach? I wonder why this is not supported currently.
Thanks