如何序列化具有未导出字段的复杂接口?
我需要序列化一些复杂的接口(template.Template)。它有许多未导出的字段,gob 不想与它们合作。有什么建议吗?
PS 实际上,我试图将解析后的模板放入 App Engine 上的内存缓存中。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简而言之,未导出字段通常是有原因的 -
template.Template
包含在解析过程中发生变化的信息,因此我建议不要使用reflect
自行序列化它们。但是,GobEncoder
和GobDecoder
接口最近已添加到gob
中;如果您需要序列化具有未导出字段的复杂结构,请鼓励包的作者实现这些接口。更好的是,您自己实现它们(对于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 withreflect
. However, theGobEncoder
andGobDecoder
interfaces were recently added togob
; 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 fortemplate.Template
) and contribute your patch.如果类型来自另一个包(例如模板),则无法使用任何当前的 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
, specificallyValue.Field()
and friends to get the unexported fields. Then you just need to store them in a way that you can decode later.