Generics

177 views
Skip to first unread message

Jérôme LAFORGE

unread,
May 27, 2022, 11:53:10 AM5/27/22
to golang-nuts
Hello,
I do some tests with generics with Go 1.18.
But I can't reach my goal.

I have:
```
panic: json: Unmarshal(nil *main.payload)

goroutine 1 [running]:
main.main()
	/tmp/sandbox3884661607/prog.go:43 +0x112

Program exited.
```

Because payload (line 15) is nil

Any tips ?

Many thx.

Martin Schnabel

unread,
May 27, 2022, 12:25:25 PM5/27/22
to golan...@googlegroups.com
how about https://go.dev/play/p/YXOTLKpvXNI using json unmarshal
directly and without using binary marshaller.

or even https://go.dev/play/p/GFE3rnyx9f8 without the endpoint abstraction.

or maybe explain what you want to achieve other than unmarshalling a
json payload?

best regards
> --
> 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
> <mailto:golang-nuts...@googlegroups.com>.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/5cd2414a-ee8d-4a32-b976-d8b97d677945n%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/5cd2414a-ee8d-4a32-b976-d8b97d677945n%40googlegroups.com?utm_medium=email&utm_source=footer>.

Martin Schnabel

unread,
May 27, 2022, 12:32:56 PM5/27/22
to golan...@googlegroups.com
the reason your snippet does not work is that you pass in *payload as T
and the zero value of a pointer type is nil and json unmarshal cannot
with nil pointer values. so would need to pass in payload as T and
*payload as P and somehow explain that P is *T and a
encoding.BinaryUnmarshaler. I am not versed enough in go generics to
know the solution, but would propose to take a simpler approach if possible.

Sebastien Binet

unread,
May 27, 2022, 1:21:43 PM5/27/22
to Martin Schnabel, golan...@googlegroups.com
what you may be looking at is (in the words of Rog Peppe) "structural
type constraints":

https://go.dev/play/p/HiFc9CUfI7P

-s
> an email to golang-nuts...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/2aea3b7e-a34e-fe5f-be44-ba4432d46ee2%40mb0.org.

Jérôme LAFORGE

unread,
May 28, 2022, 3:30:14 AM5/28/22
to golang-nuts
I use binary marshaller interface because payload is not encoded into json only (xml, binary or whatever).

I have already classic solution that works but I just want to test in order to see how generics can impact it.

Jérôme LAFORGE

unread,
May 28, 2022, 3:34:13 AM5/28/22
to golang-nuts
Thanks Sebastien
Reply all
Reply to author
Forward
0 new messages