如何序列化/反序列化go中的地图 [英] how to serialize/deserialize a map in go

查看:141
本文介绍了如何序列化/反序列化go中的地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的直觉告诉我,它不得不被转换成一个字符串或字节[](这可能与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.

我发现这个软件包( http://golang.org/pkg /编码/ gob / ),但它看起来像它只是结构?

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

推荐答案

序列化数据,Go为此提供了许多软件包。一些常见编码方式的包:

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

编码/ gob


encoding / xml

编码/ json

encoding / gob 句柄贴图很好。下面的例子显示了map的编码/解码:

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\n", decodedMap)
}

游乐场

这篇关于如何序列化/反序列化go中的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆