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

kevinburke opened this issue Nov 3, 2016 · 1 comment


Copy link

@kevinburke kevinburke commented Nov 3, 2016

Can I do

enc := gob.NewEncoder(w)

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.

Copy link
Contributor Author

@kevinburke kevinburke commented Nov 3, 2016

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.

@kevinburke kevinburke closed this Nov 3, 2016
@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.
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants
You can’t perform that action at this time.