Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 837
lollercoaster Avatar asked Nov 04 '13 05:11

lollercoaster


2 Answers

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

like image 136
ANisus Avatar answered Oct 03 '22 07:10

ANisus


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.

like image 45
Crimson Avatar answered Oct 03 '22 06:10

Crimson