1 回答

TA貢獻1806條經驗 獲得超8個贊
簡而言之:編碼/二進制不能用于編碼具有非固定大小的任意值。 就是這樣的例子。引用自二進制。寫():intstring
Write 將數據的二進制表示形式寫入 w。數據必須是固定大小的值或固定大小的值的切片,或者是指向此類數據的指針。
請注意,如果刪除該字段并將字段更改為 ,它將起作用:stringintint32
type Stu struct {
Age int32
Id int32
}
func main() {
s := &Stu{
Age: 21,
Id: 1,
}
buf := new(bytes.Buffer)
err := binary.Write(buf, binary.BigEndian, s)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%q\n", buf)
}
哪些輸出(在Go Playground上嘗試):
"\x00\x00\x00\x15\x00\x00\x00\x01"
如文檔所示,要對復雜結構進行編碼,請使用編碼/gob。
使用以下內容進行編碼和解碼的示例:encoding/gob
buf := new(bytes.Buffer)
enc := gob.NewEncoder(buf)
if err := enc.Encode(s); err != nil {
fmt.Println(err)
}
fmt.Printf("%v\n", buf.Bytes())
dec := gob.NewDecoder(buf)
var s2 *Stu
if err := dec.Decode(&s2); err != nil {
fmt.Println(err)
}
fmt.Printf("%+v\n", s2)
哪些輸出(在Go Playground上嘗試):
[41 255 129 3 1 1 3 83 116 117 1 255 130 0 1 3 1 4 78 97 109 101 1 12 0 1 3 65 103 101 1 4 0 1 2 73 100 1 4 0 0 0 12 255 130 1 3 76 101 111 1 42 1 2 0]
&{Name:Leo Age:21 Id:1}
- 1 回答
- 0 關注
- 210 瀏覽
添加回答
舉報