Acessing struct field in generic

2,167 views
Skip to first unread message

Yulrizka

unread,
Feb 21, 2022, 5:41:35 AM2/21/22
to golang-nuts
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

Brian Candler

unread,
Feb 21, 2022, 7:13:24 AM2/21/22
to golang-nuts
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.

Jason Phillips

unread,
Feb 21, 2022, 7:24:16 AM2/21/22
to golang-nuts
This is https://github.com/golang/go/issues/48522 which is described in the original proposal document but was deemed inessential for the implementation in 1.18. This will likely come in a later release.
Reply all
Reply to author
Forward
0 new messages