struct - golang 将字节数组转换为结构

标签 struct go casting byte

我正在寻找一种干净的方法来将字节数组转换为客户端-服务器应用程序的结构。 我知道大多数人都转向 gob 包来解决这个问题,但是我不控制应用程序的编码。话虽这么说,我只编写了服务器应用程序而不是客户端,有一个正在交换的协议(protocol)的相互契约(Contract)。

我能得出的最好结果如下。

type T struct {
    A int16
    B int8
    C []byte
}

func main() {
    // Create a struct and write it.
    t := T{A: 99, B: 10}
    buf := &bytes.Buffer{}

    buf1 := []byte{5, 100, 100}
    fmt.Println(buf1)

    buf.Write(buf1)

    //err := binary.Write(buf, binary.BigEndian, t)

    //if err != nil {
    //  panic(err)
    //}
    fmt.Println(buf)

    // Read into an empty struct.
    t = T{}
    err := binary.Read(buf, binary.BigEndian, &t)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%d %d", t.A, t.B)
}

但是,一旦 number bytes 与结构的大小不一致,go 就会发送 panic。如果尺寸过小或过大,我如何修改它以在没有 panic 的情况下工作

Go playground

最佳答案

根据 http://golang.org/pkg/encoding/binary/#Read :

Data must be a pointer to a fixed-size value or a slice of fixed-size values.

所以你不能在你的结构中使用 slice []byte 。但是你可以为它使用固定大小的数组。
像这样:

package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
)

type T struct {
    A int16
    B int8
    C [256]byte
}

func main() {
    // Create a struct and write it.
    t := T{A: 99, B: 10}
    buf := &bytes.Buffer{}
        
    err := binary.Write(buf, binary.BigEndian, t)
    
    if err != nil {
        panic(err)
    }
    fmt.Println(buf)

    // Read into an empty struct.
    t = T{}
    err = binary.Read(buf, binary.BigEndian, &t)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%d %d", t.A, t.B)
}

Go playground

关于struct - golang 将字节数组转换为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529071/

相关文章:

c++ - 删除以结构体为键的映射时出现段错误

c - C中的位域内存使用

GO - net/http - 如何获取请求字符串和方法

java - 是否可以在 Java 中阻止/拒绝转换?

C++ void指针获取结构

ssl - Python 的 create_default_context() 等价于 Go?

go - Go中有没有打印一个对象当前所有成员名和值的函数?

java - 将不同的对象存储在从同一抽象类扩展的容器中

java - 在调用 super 之前在构造函数中转换变量?

c - 哪些项目(结构)知道它们在数组中的位置的静态数组