dongyudun6465 2014-07-25 09:29
浏览 44
已采纳

转到:读写压缩的gob到文件

This does not appear to work correctly and I'm not sure what I'm doing wrong. I'm attempting to convert a map into a gob, gzip the binary and save it to a file, then later read it back.

type Object struct {
mystruct map[string][]scorer
}

type scorer struct {
category int
score float64
}

func (t *Object) Load(filename string) error {

    fi, err := os.Open(filename)
    if err !=nil {
        return err
    }
    defer fi.Close()

    fz, err := gzip.NewReader(fi)
    if err !=nil {
        return err
    }
    defer fz.Close()

    decoder := gob.NewDecoder(fz)
    err = decoder.Decode(&t.mystruct)
    if err !=nil {
        return err
    }

    return nil
}

func (t *Object) Save(filename string) error {

    fi, err := os.Create(filename)
    if err !=nil {
        return err
    }
    defer fi.Close()

    fz := gzip.NewWriter(fi)
    defer fz.Close()

    encoder := gob.NewEncoder(fz)
    err = encoder.Encode(t.mystruct)
    if err !=nil {
        return err
    }

    return nil
}

Something is saved to a file and the gzip appears to be valid, but it is either saving nothing or not loading it back again.

I'm also not sure if I'm doing this correctly as I'm new to Go and I'm finding it difficult to get my head around the readers and writers, since I'm coming from PHP and not used to that.

Any ideas?

  • 写回答

1条回答 默认 最新

  • dongweiben5229 2014-07-25 09:47
    关注

    Your problem has nothing to do with Readers and Writers: You just cannot encode/decode fields which are un-exported and all your fields are unexported (lowercase). You'll have to use Mystruct, Categoryand Score or write your own BinaryMarshal/BinaryUnmarshal as explained in http://golang.org/pkg/encoding/gob/#example__encodeDecode

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

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。