Failed to compile a generic code using embedded struct

201 views
Skip to first unread message

Albert Widiatmoko

unread,
Feb 26, 2024, 9:44:46 AM2/26/24
to golang-nuts
Hi Go community,

I was playing with Go generics and writing some codes, but I faced some problems. I want to ask questions and help from the community if possible. Below, I am trying to build a generic struct via a method through another generic struct.

Here's the link to Go Playground: https://go.dev/play/p/Q0zOJUePkmR

---

package main

var _ I = (*A)(nil)

type I interface {
String() string
}

type A struct {
str string
}

func (a A) String() string {
return a.str
}

type AE[T, V I] struct {
T1 T
T2 V
}

// func (AE[T, V]) String() string {
// return "test"
// }

type Test[T, V A] struct{}

func (t Test[T, V]) S() AE[T, V] {
return AE[T, V]{}
}

func main() {}

---

I expected the program to run, but then I got an error:

T does not satisfy I (missing method String)

I a bit confused because A implements I interface. I think this must be because I missed something with the Go generics.

Thank you.

Sean Liao

unread,
Feb 26, 2024, 10:54:54 AM2/26/24
to golang-nuts

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/1ab4599e-1f6c-493e-85e7-11d35e77012bn%40googlegroups.com.

tapi...@gmail.com

unread,
Feb 27, 2024, 12:29:00 AM2/27/24
to golang-nuts
use

   type Test[T, V interface{A; I}] struct{}

instead now.

There are still several restrictions in custom generics: https://go101.org/generics/888-the-status-quo-of-go-custom-generics.html
Reply all
Reply to author
Forward
0 new messages