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.
On Monday, February 21, 2022 at 7:13:24 AM UTC-5 Brian Candler wrote: > 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/5bfae092-64bf-4e24-84ce-ba79165c4c51n%40googlegroups.com.