Can not convert a generic struct type to a generic interface type in golang

174 views
Skip to first unread message

Log4bob

unread,
Oct 28, 2024, 8:47:37 AMOct 28
to golang-nuts

Given there's a generic interface:

type Packet interface { Content() int } type Recycler[T any] interface { Get() *T }

and their implementation:

type packet struct { content int } type BaseRecycler[T any] struct { t T }

its impossible to convert the implementation to the interface:

r := &BaseRecycler[packet]{} r1 := r.(Recycler[Packet]) fmt.Println(r3.Get().Content()) // compile error: Unresolved reference 'Content'

here is a live code example: https://go.dev/play/p/qbnYfyDd22A

The error is because the Packet interface align with the *packet instead of packet. Could anyone suggest how to handle this?


Marvin Renich

unread,
Oct 28, 2024, 3:44:37 PMOct 28
to golan...@googlegroups.com
* Log4bob <qdon...@gmail.com> [241028 08:47]:
If you uncomment line 39 (assignment to r3), add «_ = r3» to avoid
"unused variable" error, and run it, you get a runtime panic. Your
primary problem is related to this FAQ:

https://go.dev/doc/faq#convert_slice_of_interface

because BaseRecycler[packet] is "struct { t packet }" not "struct { t
Packet }" so r is *struct { t packet }, which has a different, and
differently sized, internal representation.

What are you really trying to do?

...Marvin

Jason Phillips

unread,
Oct 28, 2024, 4:39:35 PMOct 28
to golang-nuts
The Go FAQ has another, perhaps slightly more applicable, entry:

Basically, even though *packet satisfies the Packet interface,

    interface {
        Get() *packet
    }

Is different than

    interface {
        Get() Packet
    }

And one isn't directly convertible into the other. In Go, interface signatures must match _exactly_ in order to satisfy an interface.


Jason

Jason Phillips

unread,
Oct 28, 2024, 4:56:01 PMOct 28
to golang-nuts
And by "interface signatures" I of course meant method signatures in the corresponding interface method sets.

noreply_...@shipt.com

unread,
Nov 3, 2024, 7:07:54 PMNov 3
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 visit https://groups.google.com/d/msgid/golang-nuts/8f1c7a3d-d71b-4a8b-bee8-376c2ffed215n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages