[英]how to serialize/deserialize a map in 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. 我的直觉告诉我,它必须以某种方式转换为字符串或byte [](甚至可能是Go中的相同内容?)然后保存到磁盘。
I found this package ( http://golang.org/pkg/encoding/gob/ ), but it seems like its just for structs? 我找到了这个软件包( http://golang.org/pkg/encoding/gob/ ),但它似乎只适用于结构?
There are multiple ways of serializing data, and Go offers many packages for this. 有多种方法可以序列化数据,Go为此提供了许多软件包。 Packages for some of the common ways of encoding:
一些常见编码方式的包:
encoding/gob
encoding/xml
encoding/json
encoding/gob
handles maps fine. encoding/gob
处理地图很好。 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)
}
The gob package will let you serialize maps. gob包将允许您序列化地图。 I wrote up a small example http://play.golang.org/p/6dX5SMdVtr demonstrating both encoding and decoding maps.
我写了一个小例子http://play.golang.org/p/6dX5SMdVtr,展示了编码和解码图。 Just as a heads up, the gob package can't encode everything, such as channels.
就像抬头一样,gob包不能编码所有内容,例如频道。
Edit: Also string and []byte are not the same in Go. 编辑:Go中的字符串和[]字节也不一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.