Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 将结构保存到二进制文件_Go - Fatal编程技术网

Go 将结构保存到二进制文件

Go 将结构保存到二进制文件,go,Go,我正在尝试将嵌套结构转换为二进制文件。 将来会有很多房间的记录,所以我认为二进制文件中的序列化结构是最好的方法 package main import ( "bytes" "encoding/binary" "log" "time" ) type House struct { ID int Floors int Rooms []Room } type Room struct { Width int

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

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:无效的类型main.House

有人能帮我吗,因为我找不到解决方案。

根据二进制文件。编写文档:

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

您的房屋结构不是固定大小的值

你可以单独考虑写/读房子和房间。用于存储房屋结构的房屋不能包含切片,因此可以声明用于从文件读/写的另一房屋结构

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