Gob Round Trips Composite Values

encoding/gob serializes structs with maps and slices into a byte stream and restores them into fresh values with deep-copied composite fields.

GoData Integrity

Code

gosnippet
39 lines
package main

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

type Snapshot struct {
	Name   string
	Scores map[string]int
	Tags   []string
}

func main() {
	sent := Snapshot{
		Name:   "stage-1",
		Scores: map[string]int{"lint": 98, "unit": 87},
		Tags:   []string{"ci", "nightly"},
	}

	// gob encodes into the buffer: composite values like maps and slices serialize too
	var wire bytes.Buffer
	if err := gob.NewEncoder(&wire).Encode(sent); err != nil {
		panic(err)
	}
	fmt.Println("encoded bytes:", wire.Len())

	// Decode into fresh values: field types are restored from gob's self-describing stream
	var got Snapshot
	if err := gob.NewDecoder(&wire).Decode(&got); err != nil {
		panic(err)
	}
	fmt.Println(got.Name, got.Scores["unit"], got.Tags)

	// Map and slice are deeply reconstructed: mutating the decoded value leaves the original untouched
	got.Scores["lint"] = 0
	fmt.Println("original intact:", sent.Scores["lint"])
}

How the snippet works

Count the function main as the entire surface area of Gob Round Trips Composite Values.

Every err != nil branch (2 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

Caveats

  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Taking the usage further

Running the file prints labeled results such as encoded bytes:, original intact: — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

How should callers handle failures?
By terminating the run: `panic(err)` fires at each of the 2 checks, so callers see failures only as a stopped program.
What does Gob Round Trips Composite Values print when run?
Run it as a complete program — the output lines carry labels such as `encoded bytes:`, `original intact:`.