dqxboe2628
dqxboe2628
2018-05-16 16:10
浏览 178
已采纳

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

I believe this is a legitimate use case for Gob serialization. Yet enc.Encode returns an error because Something has no exported field. Note that I’m not serializing Something directly but only Composed that contains exported fields.

The only workaround I’ve found was to add a Dummy (exported) value to Something. This is ugly. Is there a more elegant solution?

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)
    }
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanchendu69495
    duanchendu69495 2018-05-16 17:06
    已采纳

    Here are some different workarounds from that proposed in the question.

    Don't use embedding.

    type Composed struct {
        something       Something
        DataToSerialize int
    }
    
    func (c *Composed) DoSomething() { c.something.DoSomething() }
    

    playground example

    Implement GobDecoder and GobEncoder

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

    playground example

    点赞 评论

相关推荐