0

I'm trying same my nested struct to binary files. In future there will be a lots of "Rooms" records so serialized struct in binary file is the best approach I think.

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)
    }

}

But I have error: - Binary.Write: invalid type main.House

Could someone help me because I cant find solution.

1 Answer 1

1

According to the binary.Write documentation:

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

Your House structure is not a fixed size value.

You might consider writing/reading House and Room separately. The House you use to store house structs must not contain a slice, so you can declare another House struct that you use to read/write from your file.

Instead of a binary file you can store your objects as JSON, and then you wouldn't need to deal with this problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.