donglu8344812 2019-01-02 17:17
浏览 119

如何在GoLang中使用GOB编码序列化嵌套结构?

I have a couple of example nested structs and need to serialize them. I am using the encoding/gob library, which should convert the struct data to bytes and the encoding/base64 library to convert the bytes to a readable base64 format. However, when I run my example code I get a serialization error error. I don't understand why this happens and how to fix the problem.

I followed this example: Golang serialize and deserialize back

Here is the code:

package main

import (
    "bytes"
    "encoding/base64"
    "encoding/gob"
    "errors"
    "fmt"
)

type Hello struct {
    greeting string
}

type Bye struct {
    helloSaid Hello
    byesaid Hello
}


func (b1 Bye) Serialize() (string, error) {
    b := bytes.Buffer{}
    e := gob.NewEncoder(&b)
    err := e.Encode(b1)
    if err != nil {
        return string(b.Bytes()[:]), errors.New("serialization failed")
    }
    return base64.StdEncoding.EncodeToString(b.Bytes()), nil
}

func DeserializeBye(str string) (Bye, error) {
    m := Bye{}
    by, err := base64.StdEncoding.DecodeString(str)
    if err != nil {
        return m, errors.New("deserialization failed")
    }
    b := bytes.Buffer{}
    b.Write(by)
    d := gob.NewDecoder(&b)
    err = d.Decode(&m)
    if err != nil {
        return m, errors.New("deserialization failed")
    }
    return m, nil
}

func main() {
    h := Hello{greeting: "hello"}
    b := Bye{helloSaid: h, byesaid: h}
    serialized, err := b.Serialize()
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(serialized)
}
  • 写回答

1条回答 默认 最新

  • dsk49208 2019-01-02 17:46
    关注

    Please, make the fields of the Hello and Bye structures public. Please see the documentation for the gob package:

    Structs encode and decode only exported fields.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据