go - 如何告诉 Golang Gob 编码可以序列化包含没有导出字段的结构的结构
问题描述
我相信这是 Gob 序列化的合法用例。但是由于没有导出字段而enc.Encode
返回错误。Something
请注意,我不是Something
直接序列化,而是仅Composed
包含导出的字段。
我发现的唯一解决方法是将Dummy
(导出的)值添加到Something
. 这很丑陋。有没有更优雅的解决方案?
https://play.golang.org/p/0pL6BfBb78m
package main
import (
"bytes"
"encoding/gob"
)
type Something struct {
temp int
}
func (*Something) DoSomething() {}
type Composed struct {
Something
DataToSerialize int
}
func main() {
enc := gob.NewEncoder(&bytes.Buffer{})
err := enc.Encode(Composed{})
if err != nil {
panic(err)
}
}
解决方案
以下是与问题中提出的一些不同的解决方法。
不要使用嵌入。
type Composed struct {
something Something
DataToSerialize int
}
func (c *Composed) DoSomething() { c.something.DoSomething() }
func (*Something) GobDecode([]byte) error { return nil }
func (Something) GobEncode() ([]byte, error) { return nil, nil }
推荐阅读
- r - For循环从R中的数据框列表中创建相同的表
- django - 如何获取父对象中的下一个对象?
- python - 尝试使用 Helium/Selenium 登录 Instagram 时出现查找错误
- many-to-many - 我可以在我的数据仓库/表格模型中的不同字段上创建多对多关系吗?
- laravel - Laravel + Vuejs + Laravel-Webscoket + Apache
- snakemake - 在一个作业步骤中处理输入数组
- reactjs - 1.5 MB 的大请求大小和多层次的树形形式使浏览器无响应的 yield 调用
- flutter - 使用 OutlineInputBorder 从 InputDecoration 中删除 helperText 填充
- java - 如何在 py eureka 客户端中使用动态实例端口启动 django 应用程序?
- java - 为什么在返回之前将 volatile 分配给局部变量