Binary Write And Read Fixed Width Structs

Encode fixed-width structs with binary.Write and binary.Read so the on-disk layout is explicit, byte counts are predictable, and endianness stays controlled.

GoData Integrity

Code

gosnippet
32 lines
package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
)

type Header struct {
	Magic    uint16
	Version  uint8
	Reserved uint8
	Payload  uint32
}

func main() {
	h := Header{Magic: 0xBEEF, Version: 2, Reserved: 0, Payload: 1024}

	var buf bytes.Buffer
	// BigEndian 写入:字段按声明顺序、定宽落盘,不做对齐填充
	if err := binary.Write(&buf, binary.BigEndian, h); err != nil {
		panic(err)
	}
	fmt.Printf("encoded %d bytes: % x\n", buf.Len(), buf.Bytes())

	var back Header
	// Read 需要指向结构的指针,精确消费结构体大小的字节
	if err := binary.Read(&buf, binary.BigEndian, &back); err != nil {
		panic(err)
	}
	fmt.Printf("decoded: %#x v%d payload=%d\n", back.Magic, back.Version, back.Payload)
}

How the code behaves

Count the function main as the entire surface area of Binary Write And Read Fixed Width Structs.

Failure handling is panic(err): 2 checkpoints abort the program at the point a problem is detected.

What to watch for

  • The whole dependency story is the language version itself.
  • panic(err) is the only failure path here: the first problem stops the program.

Applying it

The demo output is labeled (encoded, decoded:), so every line in the printed output names the step that produced it.

Statements that matter

h := Header{Magic: 0xBEEF, Version: 2, Reserved: 0, Payload: 1024}

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
It stops. All 2 `if err != nil` branches ends in `panic(err)` — nothing continues past a failed call.
What does Binary Write And Read Fixed Width Structs print when run?
Execute the whole file; each printed line is prefixed with a label like `encoded`, `decoded:`.