如何告诉 Golang Gob 编码可以序列化包含没有导出字段的结构的结构
How to tell Golang Gob encoding that it’s ok to serialize a struct that contains a struct with no exported fields
我相信这是 Gob 序列化的合法用例。然而 enc.Encode
returns 一个错误,因为 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() }
实施GobDecoder and GobEncoder
func (*Something) GobDecode([]byte) error { return nil }
func (Something) GobEncode() ([]byte, error) { return nil, nil }
据我所知,添加函数GobDecode和GobEncode只能让编码器避免错误,但不能让它正常工作。
如果我添加一个解码操作,它似乎无法用我编码到其中的值取回 DataToSerialize 项目。
我相信这是 Gob 序列化的合法用例。然而 enc.Encode
returns 一个错误,因为 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() }
实施GobDecoder and GobEncoder
func (*Something) GobDecode([]byte) error { return nil }
func (Something) GobEncode() ([]byte, error) { return nil, nil }
据我所知,添加函数GobDecode和GobEncode只能让编码器避免错误,但不能让它正常工作。 如果我添加一个解码操作,它似乎无法用我编码到其中的值取回 DataToSerialize 项目。