英文:
how to serialize/deserialize a map in go
问题
我的直觉告诉我,它可能需要被转换成字符串或字节数组(在Go中可能是相同的东西),然后保存到磁盘上。
我找到了这个包(http://golang.org/pkg/encoding/gob/),但似乎它只适用于结构体?
英文:
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?
答案1
得分: 23
有多种序列化数据的方法,Go语言提供了许多相关的包。以下是一些常见编码方式的包:
encoding/gob
encoding/xml
encoding/json
encoding/gob
可以很好地处理映射。下面的示例展示了对映射进行编码和解码的过程:
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)
// 编码映射
err := e.Encode(m)
if err != nil {
panic(err)
}
var decodedMap map[string]int
d := gob.NewDecoder(b)
// 解码序列化的数据
err = d.Decode(&decodedMap)
if err != nil {
panic(err)
}
// 完成!这是一个映射!
fmt.Printf("%#v\n", decodedMap)
}
英文:
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)
}
答案2
得分: 9
gob包可以让你序列化映射(maps)。我写了一个小例子http://play.golang.org/p/6dX5SMdVtr,演示了如何编码和解码映射。需要注意的是,gob包不能编码所有类型,比如通道(channels)。
编辑:另外,在Go语言中,字符串(string)和字节切片([]byte)是不同的。
英文:
The gob package will let you serialize maps. I wrote up a small example http://play.golang.org/p/6dX5SMdVtr demonstrating both encoding and decoding maps. Just as a heads up, the gob package can't encode everything, such as channels.
Edit: Also string and []byte are not the same in Go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论