我正在寻找一种干净的方法来将字节数组转换为客户端-服务器应用程序的结构。 我知道大多数人都转向 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 的情况下工作
最佳答案
根据 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)
}
关于struct - golang 将字节数组转换为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529071/