Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encoding/gob: Can a single gob.Encoder encode different types of values? #17770

Closed
kevinburke opened this issue Nov 3, 2016 · 1 comment
Closed

Comments

@kevinburke
Copy link
Contributor

kevinburke commented Nov 3, 2016

Can I do

enc := gob.NewEncoder(w)
enc.Encode(time.Now())
enc.Encode(http.Response{})

I was unclear whether different structs could be encoded with the same Encoder after reading the encoding/gob documentation. I had to read the documentation several times to figure out that it was okay. This sentence especially threw me off:

is most efficient when a single Encoder is used to transmit a stream of values, amortizing the cost of compilation.

which made me think that an Encoder does some kind of internal optimizations based on the values it's encoding, and it's bad, or erroring, to transmit different struct types with the same Encoder.

In particular I am gob.Encoding three different structs in my code and I'm trying to decide whether I should just create a new gob.Encoder each time I have to encode something, or whether it's worth it to create one and use it to encode the three different structs. I am imagining it's possible the Encoder has some kind of design where the codec gets clobbered/reoptimized each time it encounters a different struct, so it's easier to just create a new one each time. I don't know if that's true or not.

I understand there is a value judgement here, to me these docs could be a little more clear. Feel free to close.

@kevinburke
Copy link
Contributor Author

Sorry, ignore this. I can't even reuse a gob.Encoder, because I can't reuse the underlying Writer to write two different datatypes. I only use a Writer to write one value at a time, so I have to use a new Encoder each time, I believe.

@golang golang locked and limited conversation to collaborators Nov 3, 2017
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants