Serialization
Serialization Philosophy
Section titled “Serialization Philosophy”Serialization always uses the raw value — never the brand prefix. So "user-123", not "User:user-123".
Zero values serialize to null / nil across all formats.
type UserBrand struct{}func (UserBrand) Name() string { return "User" }type UserID = id.ID[UserBrand, string]
// MarshaluserID := id.NewID[UserBrand]("user-123")data, _ := json.Marshal(userID)fmt.Println(string(data)) // "user-123"
// Zero value → nullvar empty UserIDdata, _ = json.Marshal(empty)fmt.Println(string(data)) // null
// Unmarshalvar parsed UserIDjson.Unmarshal([]byte(`"user-456"`), &parsed)fmt.Println(parsed.Get()) // user-456
// Unmarshal null → zero valuejson.Unmarshal([]byte(`null`), &parsed)fmt.Println(parsed.IsZero()) // trueUses
encoding/json/v2— requiresGOEXPERIMENT=jsonv2.
Works directly with database/sql:
// Scan from databasevar userID UserIDrow.Scan(&userID)
// Save to databasedb.Exec("INSERT INTO users (id, name) VALUES (?, ?)", userID, "John")
// Zero value → NULLvar empty UserIDdb.Exec("INSERT INTO orders (user_id) VALUES (?)", empty) // inserts NULLScan accepts string, []byte, int64, int, and float64 from database drivers and casts to the target type. Value returns the correct driver.Value for the underlying type.
Text (XML, TOML)
Section titled “Text (XML, TOML)”// Marshal to textdata, _ := userID.MarshalText()fmt.Println(string(data)) // user-123
// Unmarshal from textvar parsed UserIDparsed.UnmarshalText([]byte("user-456"))Binary
Section titled “Binary”Little-endian encoding for all numeric types. int and uint are serialized as 8 bytes (uint64).
// Marshal to binarydata, _ := userID.MarshalBinary()
// Unmarshal from binaryvar parsed UserIDparsed.UnmarshalBinary(data)Gob encoding delegates to binary marshaling:
// Register the type before encodinggob.Register(UserID{})
// Encodebuf := new(bytes.Buffer)enc := gob.NewEncoder(buf)enc.Encode(userID)
// Decodedec := gob.NewDecoder(buf)var parsed UserIDdec.Decode(&parsed)Summary
Section titled “Summary”| Format | Interfaces | Zero Value |
|---|---|---|
| JSON | MarshalJSON / UnmarshalJSON |
null |
| SQL | Scan / Value |
nil |
| Text | MarshalText / UnmarshalText |
nil |
| Binary | MarshalBinary / UnmarshalBinary |
empty bytes |
| Gob | GobEncode / GobDecode |
delegates to binary |