简体   繁体   中英

How to encode struct to byte slice and decode byte slice back to original struct using gob encoding?

i am trying marshall go struct to bytes (via gob encoding), and then to unmarshall those bytes back to original object. I am getting unexpected result (object is not getting the correct values). Help me to correct the programm please.

Input:

package main

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

type object struct {
    name string
    age  int
}

func main() {
    inputObject := object{age: 22, name: "Zloy"}
    fmt.Println(inputObject)

    var inputBuffer bytes.Buffer
    gob.NewEncoder(&inputBuffer).Encode(inputObject)
    fmt.Println(inputBuffer)

    destBytes := inputBuffer.Bytes()
    fmt.Println("\n", destBytes, "\n")

    var outputBuffer bytes.Buffer
    outputBuffer.Write(destBytes)
    fmt.Println(outputBuffer)

    var outputObject object
    gob.NewDecoder(&outputBuffer).Decode(&outputObject)
    fmt.Println(outputObject)
}

Output:

{Zloy 22}
{[18 255 129 3 1 1 6 111 98 106 101 99 116 1 255 130 0 0 0] 0 0}

 [18 255 129 3 1 1 6 111 98 106 101 99 116 1 255 130 0 0 0]     

{[18 255 129 3 1 1 6 111 98 106 101 99 116 1 255 130 0 0 0] 0 0}
{ 0}

Expected Output:

{Zloy 22}
{[18 255 129 3 1 1 6 111 98 106 101 99 116 1 255 130 0 0 0] 0 0}

 [18 255 129 3 1 1 6 111 98 106 101 99 116 1 255 130 0 0 0]     

{[18 255 129 3 1 1 6 111 98 106 101 99 116 1 255 130 0 0 0] 0 0}
{Zloy 22}

You need to capitalize the field names to make them publicly exportable/importable:

type object struct {
    Name string
    Age  int
}

https://play.golang.org/p/_YqSmeDi6oH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM