Strings encode/decode in gob

1.1k Views Asked by At

I followed https://blog.golang.org/gob link. and wrote a sample, where the structure has all string data. Here is my sample:

package main

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

type P struct {
    X string
    a string
    Name    string

}

type Q struct {
    X string
    a string
    Name string

}

func main() {
    // Initialize the encoder and decoder.  Normally enc and dec would be
    // bound to network connections and the encoder and decoder would
    // run in different processes.
    var network bytes.Buffer        // Stand-in for a network connection
    enc := gob.NewEncoder(&network) // Will write to network.
    dec := gob.NewDecoder(&network) // Will read from network.
    // Encode (send) the value.
    err := enc.Encode(P{"My string", "Pythagoras","a string"})
    if err != nil {
        log.Fatal("encode error:", err)
    }
    // Decode (receive) the value.
    var q Q
    err = dec.Decode(&q)
    if err != nil {
        log.Fatal("decode error:", err)
    }
    fmt.Println(q.X,q.Name)
    fmt.Println(q.a)
}

The play golang : https://play.golang.org/p/3aj0hBG7wMj

The expected output :

My string a string
Pythagoras

The actual output

My string a string

I don't know why the "pythagoras" string is missing from the output. I observed similar behavior when I have multiple strings, integers data in structures, and processed with gob.

How strings are processed? What is the issue in my program?

4

There are 4 best solutions below

0
On BEST ANSWER

Your a field is unexported (has a name starting with a lowercase letter). Go's reflection, and by extension marshallers like JSON, YAML, and gob, can't access unexported struct fields, only exported ones.

0
On

The gob codec ignores unexported fields. Export the field by capitalizing the first letter in the field name:

type P struct {
    X string
    A string
    Name string
}

Make a similar change to type Q.

Run it on the playground.

0
On

The fields you assign the value "Pythagoras" to names must be exported.

type P struct {
    X string
    a string // --> change name to A
    Name    string
}

type Q struct {
    X string
    a string // --> change name to A
    Name string
}

In the blog post you linked, it is documented (Ctrl+F for "exported"):

Only exported fields are encoded and decoded.

0
On

Make your a field in struct P and Q public. Then it will be encoded and decoded.

type P struct {
    X string
    A string
    Name    string

}

type Q struct {
    X string
    A string
    Name string

}