how to serialize/deserialize a map in go

huangapple go评论92阅读模式
英文:

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)
}

Playground

英文:

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)
}

Playground

答案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.

huangapple
  • 本文由 发表于 2013年11月4日 13:55:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/19762413.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定