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 python怎么在已有视频文件后添加新帧
  • ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
  • ¥15 fluent里模拟降膜反应的UDF编写
  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
  • ¥15 神经网络模型一直不能上GPU
  • ¥15 pyqt怎么把滑块和输入框相互绑定,求解决!
  • ¥20 wpf datagrid单元闪烁效果失灵