0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.