首页 > 解决方案 > 如何告诉 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)
    }
}

标签: gogob

解决方案


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

不要使用嵌入。

type Composed struct {
    something       Something
    DataToSerialize int
}

func (c *Composed) DoSomething() { c.something.DoSomething() }

游乐场示例

实现GobDecoderGobEncoder

func (*Something) GobDecode([]byte) error     { return nil }
func (Something) GobEncode() ([]byte, error) { return nil, nil }

游乐场示例


推荐阅读