简体   繁体   中英

Strings encode/decode in gob

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?

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 .

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.

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.

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

}

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