5

我相信这是 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)
    }
}
4

2 回答 2

5

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

不要使用嵌入。

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 }

游乐场示例

于 2018-05-16T17:06:31.863 回答
0

据我所知,添加函数 GobDecode 和 GobEncode 只允许编码器避免错误,但不允许它正常工作。如果我添加一个 Decode 操作,它似乎不会将 DataToSerialize 项与我编码到其中的值一起返回。

游乐场示例

于 2020-09-17T23:07:59.057 回答