dongtangyi8962 2016-03-28 13:04
浏览 54
已采纳

Go语言中的地图序列化和反序列化问题

I am doing the basic serialization and deserialization of map as suggested in this example. But I get the following error:

panic: EOF

goroutine 1 [running]:
main.load(0x81147e0, 0x1840a378)
    /home/naresh/Desktop/Work/GoEventHandler/test.go:39 +0x2cf
main.main()
    /home/naresh/Desktop/Work/GoEventHandler/test.go:16 +0xe5
exit status 2

Can anyone tell me what I am doing wrong in the following code:

package main

import (
    "fmt"
    "bytes"
    "encoding/gob"
)

func main() {   
    org := map[string]string{"hello": "world"}
    store(org)

    var loadedMap map[string]string
    load(&loadedMap)

    fmt.Println(loadedMap)   
}

func store(data interface{}) {
    m := new(bytes.Buffer) 
    enc := gob.NewEncoder(m)

    err := enc.Encode(data)
    if err != nil {
        panic(err)
    }
}

func load(e interface{}) {        
    p := new(bytes.Buffer) 
    dec := gob.NewDecoder(p)

    err := dec.Decode(e)
    if err != nil {
        panic(err)
    }
}
  • 写回答

1条回答 默认 最新

  • dongzhiman2162 2016-03-28 13:18
    关注

    Decoding is a process that requires the encoded information which will be in buffer used for encoding. Pass that to the decoder.

    package main
    
    import (
        "bytes"
        "encoding/gob"
        "fmt"
    )
    
    func main() {
        org := map[string]string{"hello": "world"}
        buf := store(org)
    
        loadedMap := make(map[string]string)
        load(&loadedMap, buf)
    
        fmt.Println(loadedMap)
    }
    
    func store(data interface{}) *bytes.Buffer {
        m := new(bytes.Buffer)
        enc := gob.NewEncoder(m)
    
        err := enc.Encode(data)
        if err != nil {
            panic(err)
        }
        return m
    }
    
    func load(e interface{}, buf *bytes.Buffer) {
        dec := gob.NewDecoder(buf)
    
        err := dec.Decode(e)
        if err != nil {
            panic(err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 对语音信号进行变调时,间接改变时序从而实现语音变速,进而将变调与变速同时实现、参数合成法换为波形合成法
  • ¥15 Python实现hog特征图可视化
  • ¥30 德飞莱51单片机实现C4炸弹
  • ¥50 CrossLink-LIF-MD6000 型 FPGA 的 CMOS 转 MIPI D-PHY IP 核功能使用异常
  • ¥15 proteus控制16x16LED点阵显示屏的设计
  • ¥30 求会做山景bp1048b2程序的。做直播声卡用
  • ¥15 求数学建模论文问题指导
  • ¥15 51单片机与数码管实现电子琴
  • ¥15 h3.6m 人类行为预测论文复现