簡體   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