如何告诉 Golang Gob 编码可以序列化包含没有导出字段的结构的结构

Fra*_*nin 5 go 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*món 5

以下是问题中提出的一些不同的解决方法。

不要使用嵌入。

type Composed struct {
    something       Something
    DataToSerialize int
}

func (c *Composed) DoSomething() { c.something.DoSomething() }
Run Code Online (Sandbox Code Playgroud)

游乐场示例

实现GobDecoderGobEncoder

func (*Something) GobDecode([]byte) error     { return nil }
func (Something) GobEncode() ([]byte, error) { return nil, nil }
Run Code Online (Sandbox Code Playgroud)

游乐场示例