Just to add an observation, it also doesn't work if you embed the struct:

type A struct {
        x int
}

type B struct {
        A
}

...even though in non-generic code m.x would be valid if m is of type B.

On Monday, 21 February 2022 at 10:41:35 UTC Yulrizka wrote:

> 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 
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/c38d7692-acae-46d8-ac19-4cd95f930939n%40googlegroups.com.

Reply via email to