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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵