繁体   English   中英

gob中的字符串编码/解码

[英]Strings encode/decode in gob

我关注了 https://blog.golang.org/gob链接。 并编写了一个示例,其中结构包含所有字符串数据。 这是我的示例:

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)
}

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

预期的 output:

My string a string
Pythagoras

实际output

My string a string

我不知道为什么 output 中缺少“pythagoras”字符串。 当我在结构中有多个字符串、整数数据并使用 gob 处理时,我观察到了类似的行为。

如何处理字符串? 我的程序有什么问题?

gob 编解码器忽略未导出的字段。 通过将字段名称中的第一个字母大写来导出字段:

type P struct {
    X string
    A string
    Name string
}

对类型Q进行类似的更改。

在操场上运行它

a字段未导出(名称以小写字母开头)。 Go 的反射,以及像 JSON、YAML 和 gob 这样的扩展编组器,无法访问未导出的结构字段,只能访问导出的字段。

必须导出为名称分配值"Pythagoras"的字段。

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
}

在您链接的博客文章中,记录了它(Ctrl+F 表示“导出”):

只有导出的字段被编码和解码。

公开 struct PQ中的a字段。 然后它将被编码和解码。

type P struct {
    X string
    A string
    Name    string

}

type Q struct {
    X string
    A string
    Name string

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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