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

如何告诉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 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!