登录
首页 >  Golang >  Go问答

how to serialize/deserialize a map in go

来源:Golang技术栈

时间:2023-04-14 10:13:38 293浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《how to serialize/deserialize a map in go》,介绍一下golang,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

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?

正确答案

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

今天关于《how to serialize/deserialize a map in go》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表