来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《how to serialize/deserialize a map in go》,介绍一下golang,希望对大家的知识积累有所帮助,助力实战开发!
问题内容
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?
正确答案
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\n", decodedMap)
}
今天关于《how to serialize/deserialize a map in go》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
