how to serialize/deserialize a map in go

前端 未结 2 1729
清歌不尽
清歌不尽 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

提交回复
热议问题