dqxboe2628 2018-05-16 08: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 09: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

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

报告相同问题?

悬赏问题

  • ¥15 FPGA芯片60进制计数器
  • ¥15 前端js怎么实现word的.doc后缀文件在线预览
  • ¥20 macmin m 4连接iPad
  • ¥15 DBIF_REPO_SQL_ERROR
  • ¥15 根据历年月数据,用Stata预测未来六个月汇率
  • ¥15 DevEco studio开发工具 真机联调找不到手机设备
  • ¥15 请教前后端分离的问题
  • ¥100 冷钱包突然失效,急寻解决方案
  • ¥15 下载honeyd时报错 configure: error: you need to instal a more recent version of libdnet
  • ¥15 距离软磁铁一定距离的磁感应强度大小怎么求
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部