英文:
How to serialize a complex interface with unexported fields?
问题
我需要对一些复杂的接口(template.Template)进行序列化。它有许多未导出的字段,而gob不愿意与它们一起工作。有什么建议吗?
附注:实际上,我正在尝试将解析后的模板放入App Engine上的内存缓存(memcache)中。
英文:
I need to serialize some complex interface (template.Template). It has many unexported fields, and gob don't want to work with them. Any suggestions?
P.S. Actualy, I trying to put a parsed template to memcache on App Engine.
答案1
得分: 5
简短的回答是,未导出字段通常有其原因 - 例如,template.Template
包含在解析过程中会发生变化的信息 - 因此,我建议不要使用 reflect
自己对其进行序列化。然而,最近在 gob
中添加了 GobEncoder
和 GobDecoder
接口;如果您需要序列化带有未导出字段的复杂结构体,请鼓励包的作者实现这些接口。更好的做法是自己实现它们(对于 template.Template
来说应该不难),并且贡献您的补丁。
英文:
The short answer is that there's usually a reason for unexported fields--template.Template
, for instance, contains information which changes during parsing--so I'd advise against serializing them yourself with reflect
. However, the GobEncoder
and GobDecoder
interfaces were recently added to gob
; if you need to serialize a complex struct with unexported fields, encourage the author of the package to implement these interfaces. Even better, implement them yourself (shouldn't be hard for template.Template
) and contribute your patch.
答案2
得分: 1
如果类型来自另一个包(例如模板),则无法使用Go的任何当前序列化库(gob
,json
,bson等)完成此操作。也不应该这样做,因为这些字段是未导出的。
但是,如果确实需要,您可以使用reflect
包编写自己的序列化器,具体使用Value.Field()
和相关方法来获取未导出的字段。然后,您只需要以一种可以稍后解码的方式存储它们。
英文:
If the type is from another package (such as template) this can't be done with any of the current serialization libs for Go (gob
, json
, bson, etc.). Nor should it be done, because the fields are unexported.
However, if you really need to, you can write your own serializer using package reflect
, specifically Value.Field()
and friends to get the unexported fields. Then you just need to store them in a way that you can decode later.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论