登录
首页 >  Golang >  Go问答

Golang Gob 解码不解码字节数组

来源:stackoverflow

时间:2024-02-10 11:15:27 414浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《Golang Gob 解码不解码字节数组》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

我正在尝试解码 inv 结构,但解码相同的编码值会返回不同的值。

// inv struct
type Inv struct {
    AddrFrom string
    Type     int
    data     [][]byte  
}


inv := Inv{
    AddrFrom: nodeAddress,
    Type:     kind,
    data:     inventories,
}
data := GobEncode(inv)
var payload Inv
gob.NewDecoder(bytes.NewBuffer(data)).Decode(&payload)

这里的payload和inv有不同的值。当 inv 结构的解码数据字段长度为零时。


正确答案


https://pkg.go.dev/encoding/gob

chan 或 func 类型的结构字段将被完全视为未导出字段并被忽略。

https://go.dev/ref/spec#Exported_identifiers

可以导出标识符以允许从另一个包访问它。如果满足以下条件,则导出标识符:

  • 标识符名称的第一个字符是 unicode 大写字母(unicode 类“lu”);和
  • 标识符在包块中声明,或者是字段名称或方法名称。

不会导出所有其他标识符。

https://pkg.go.dev/encoding/gob#hdr-Types_and_Values

gob 可以通过按优先顺序调用相应的方法来对实现 gobencoder 或 encoding.binarymarshaler 接口的任何类型的值进行编码。

Internally,gob 包依赖于 reflect 包,该包的设计遵循可见性原则。因此,gob 包不会自动处理这些字段,它需要您编写专门的实现。

https://pkg.go.dev/encoding/gob#GobEncoder

gobencoder 是描述数据的接口,它提供自己的编码值表示形式,以便传输到 gobdecoder。实现 gobencoder 和 gobdecoder 的类型可以完全控制其数据的表示,因此可能包含私有字段、通道和函数等内容,这些内容通常不能在 gob 流中传输。

示例

package main

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

// The Vector type has unexported fields, which the package cannot access.
// We therefore write a BinaryMarshal/BinaryUnmarshal method pair to allow us
// to send and receive the type with the gob package. These interfaces are
// defined in the "encoding" package.
// We could equivalently use the locally defined GobEncode/GobDecoder
// interfaces.
type Vector struct {
    x, y, z int
}

func (v Vector) MarshalBinary() ([]byte, error) {
    // A simple encoding: plain text.
    var b bytes.Buffer
    fmt.Fprintln(&b, v.x, v.y, v.z)
    return b.Bytes(), nil
}

// UnmarshalBinary modifies the receiver so it must take a pointer receiver.
func (v *Vector) UnmarshalBinary(data []byte) error {
    // A simple encoding: plain text.
    b := bytes.NewBuffer(data)
    _, err := fmt.Fscanln(b, &v.x, &v.y, &v.z)
    return err
}

// This example transmits a value that implements the custom encoding and decoding methods.
func main() {
    var network bytes.Buffer // Stand-in for the network.

    // Create an encoder and send a value.
    enc := gob.NewEncoder(&network)
    err := enc.Encode(Vector{3, 4, 5})
    if err != nil {
        log.Fatal("encode:", err)
    }

    // Create a decoder and receive a value.
    dec := gob.NewDecoder(&network)
    var v Vector
    err = dec.Decode(&v)
    if err != nil {
        log.Fatal("decode:", err)
    }
    fmt.Println(v)

}

由于字段类型已经是字节切片,您实际上只是遇到了可见性访问问题和专用的所需编组实现,虽然有争议,因为您也可以导出该字段,但应该很简单。

理论要掌握,实操不能落!以上关于《Golang Gob 解码不解码字节数组》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>