将结构保存到二进制文件



我正在尝试将我的嵌套结构与二进制文件相同。 将来会有很多"房间"记录,所以我认为二进制文件中的序列化结构是最好的方法。

package main
import (
"bytes"
"encoding/binary"
"log"
"time"
)
type House struct {
ID     int
Floors int
Rooms  []Room
}
type Room struct {
Width       int
Height      int
Description string
CreatedAt   time.Time
}
func main() {
var house House = House{
ID: 1,
Floors: 3,
}
house.Rooms = append(house.Rooms, Room{Width: 20, Height: 30, CreatedAt: time.Now(), Description: "This is description"})
house.Rooms = append(house.Rooms, Room{Width: 14, Height: 21, CreatedAt: time.Now(), Description: "This is other description"})
house.Rooms = append(house.Rooms, Room{Width: 12, Height: 43, CreatedAt: time.Now(), Description: "This is other desc"})
log.Println(house)
buf := new(bytes.Buffer)
err := binary.Write(buf, binary.LittleEndian, house)
if err != nil {
log.Println(err)
}
}

但我有错误: - 二进制.写入:无效类型主。房子

有人可以帮助我,因为我找不到解决方案。

根据binary.Write文档:

数据必须是固定大小的值或固定大小值的切片,或者指向此类数据的指针。

House结构不是固定大小值。

您可以考虑分别编写/阅读HouseRoom。用于存储房屋结构的House不得包含切片,因此可以声明另一个用于读取/写入文件的House结构。

您可以将对象存储为 JSON 而不是二进制文件,这样就不需要处理此问题了。

最新更新