gob: decoding into local type []float64, received remote type []float

653 views
Skip to first unread message

cpu...@gmail.com

unread,
Nov 28, 2021, 3:10:37 PM11/28/21
to golang-nuts
I'm trying to transfer arbitrary structs over gRPC. To achieve this I've trying to use gob for encoding the interface{} part of the structs. The code looks somewhat like https://go.dev/play/p/4Q5CQE4Wcy2 but not entirely.

Two things strike me strange:
- I receive "gob: decoding into local type []float64, received remote type []float" during Decode when the interface is a []float64
- I need to use &res.Val (which is an interface) or it will stay nil. Using res.Val (which imho works with JSON when the target is an interface) does always lead to nil result.

I would appreciate any hint how to gRPC or gob.Encode interfaces properly.

Cheers,
Andi

cpu...@gmail.com

unread,
Nov 29, 2021, 3:51:19 AM11/29/21
to golang-nuts
Turns out that the decoding problem only exist when I reuse the encoder:

b := new(bytes.Buffer)
enc := gob.NewEncoder(b)

for param := range in {
b.Reset()
if err := enc.Encode(&param.Val); err != nil {
panic(err)
}

// send encoded data
}

When I create a new encode inside the loop things are fine. I couldn't find anything regarding enc that should prevent reusing it?

Cheers,
Andi

Rob Pike

unread,
Nov 29, 2021, 5:00:19 AM11/29/21
to cpu...@gmail.com, golang-nuts
The encoder delivers a stream that includes type information. If you
reuse the stream to a different decoder, that decoder will not have
seen the type information sent to the first one.

Or to look at it another way, the encoder just sends the values you
give it, along with any type information that has not already been
transmitted. In effect, it can't tell the difference between calling
it twice to deliver to one encoder and calling it twice to deliver to
two decoders.

Don't reuse the encoder.

-rob
> --
> 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/589e4ba5-afe4-4cee-9398-326478171492n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages