doujingqu3030 2013-11-04 05:55
浏览 38
已采纳

如何在go中序列化/反序列化地图

My instinct tells me that somehow it would have to be converted to a string or byte[] (which might even be the same things in Go?) and then saved to disk.

I found this package (http://golang.org/pkg/encoding/gob/), but it seems like its just for structs?

  • 写回答

2条回答 默认 最新

  • dpwqicw157673 2013-11-04 07:21
    关注

    There are multiple ways of serializing data, and Go offers many packages for this. Packages for some of the common ways of encoding:

    encoding/gob
    encoding/xml
    encoding/json

    encoding/gob handles maps fine. The example below shows both encoding/decoding of a map:

        package main
    
    import (
        "fmt"
        "encoding/gob"
        "bytes"
    )
    
    var m = map[string]int{"one":1, "two":2, "three":3}
    
    func main() {
        b := new(bytes.Buffer)
    
        e := gob.NewEncoder(b)
    
        // Encoding the map
        err := e.Encode(m)
        if err != nil {
            panic(err)
        }
    
        var decodedMap map[string]int
        d := gob.NewDecoder(b)
    
        // Decoding the serialized data
        err = d.Decode(&decodedMap)
        if err != nil {
            panic(err)
        }
    
        // Ta da! It is a map!
        fmt.Printf("%#v
    ", decodedMap)
    }
    

    Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊