how to serialize/deserialize a map in go

前端 未结 2 1728
清歌不尽
清歌不尽 2021-02-07 07:07

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

相关标签:
2条回答
  • 2021-02-07 07:41

    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

    0 讨论(0)
  • 2021-02-07 07:59

    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.

    0 讨论(0)
提交回复
热议问题