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.
Code
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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.