Documentation
¶
Overview ¶
Package id provides branded, strongly-typed identifiers that prevent mixing different entity IDs at compile time using phantom types.
Type Safety ¶
The ID type uses phantom typing (brand types) to create distinct identifier types that cannot be accidentally mixed:
type UserBrand struct{}
type OrderBrand struct{}
type UserID = ID[UserBrand, string]
type OrderID = ID[OrderBrand, int64]
func ProcessUser(id UserID) { ... }
func ProcessOrder(id OrderID) { ... }
userID := NewID[UserBrand]("user-123")
orderID := NewID[OrderBrand, int64](456)
ProcessUser(userID) // OK
ProcessUser(orderID) // Compile error: type mismatch
Named Brands ¶
Brand types can implement the BrandNamer interface to provide a human-readable name. This makes IDs debug-visible: ID.String returns "User:abc123" instead of just "abc123", and ValidateID produces brand-aware error messages.
type UserBrand struct{}
func (UserBrand) Name() string { return "User" }
Serialization ¶
ID supports multiple serialization formats. Serialization always uses the raw value (no brand prefix):
- JSON: string-based IDs serialize as strings, numeric IDs as numbers
- Text (XML/TOML): string-based IDs only
- SQL: string, int64, int32, uint64 types supported
- Binary: efficient binary representation
- Gob: Go-specific encoding
Index ¶
- Variables
- func BrandName[B any]() string
- func MustValidateID[B any, V comparable](id ID[B, V])
- func ValidateID[B any, V comparable](id ID[B, V]) error
- func ValidateIDWithValue[B any, V comparable](id ID[B, V], validate func(V) error) error
- type BrandNamer
- type ID
- func (id ID[B, V]) Compare(other ID[B, V]) (int, error)
- func (id ID[B, V]) Equal(other ID[B, V]) bool
- func (id ID[B, V]) Format(f fmt.State, verb rune)
- func (id ID[B, V]) Get() V
- func (id ID[B, V]) GoString() string
- func (id *ID[B, V]) GobDecode(data []byte) error
- func (id ID[B, V]) GobEncode() ([]byte, error)
- func (id ID[B, V]) IsZero() bool
- func (id ID[B, V]) MarshalBinary() ([]byte, error)
- func (id ID[B, V]) MarshalJSON() ([]byte, error)
- func (id ID[B, V]) MarshalText() ([]byte, error)
- func (id ID[B, V]) Or(defaultValue ID[B, V]) ID[B, V]
- func (id ID[B, V]) Ptr() *ID[B, V]
- func (id *ID[B, V]) Reset()
- func (id *ID[B, V]) Scan(src any) error
- func (id ID[B, V]) String() string
- func (id *ID[B, V]) UnmarshalBinary(data []byte) error
- func (id *ID[B, V]) UnmarshalJSON(data []byte) error
- func (id *ID[B, V]) UnmarshalText(data []byte) error
- func (id ID[B, V]) Value() (driver.Value, error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidID is returned when ID validation fails (zero value). ErrInvalidID = errors.New("id: invalid") // ErrNotOrdered is returned when Compare is called on an ID with a non-ordered value type. ErrNotOrdered = errors.New("id: Compare requires an ordered type (int, uint, or string)") // ErrUnsupportedType is returned when a serialization format does not support // the ID's value type V (e.g., a struct passed to binary marshaling). ErrUnsupportedType = errors.New("id: unsupported type") // ErrCannotScan is returned when a SQL source value cannot be scanned into the // ID because the source type does not match the target value type. ErrCannotScan = errors.New("id: cannot scan") // ErrInsufficientData is returned when binary data is too short to decode a value. ErrInsufficientData = errors.New("id: insufficient data") // ErrInternal is returned for unreachable internal errors, such as a type // assertion that the type switch should have guaranteed. ErrInternal = errors.New("id: internal error") // ErrNilReceiver is returned when a method is called on a nil pointer receiver. ErrNilReceiver = errors.New("id: nil receiver") // ErrMarshal is returned when marshaling an ID's value to a serialization format // fails because the value type's own marshaler (encoding.TextMarshaler, // encoding.BinaryMarshaler, json.Marshaler) returned an error. ErrMarshal = errors.New("id: marshal failed") // ErrUnmarshal is returned when unmarshaling data into an ID fails because the // value type's own unmarshaler returned an error, or because the text/JSON input // could not be parsed as the target value type. ErrUnmarshal = errors.New("id: unmarshal failed") )
Sentinel errors returned by ID operations. Match with errors.Is to branch on error category; call sites wrap them with fmt.Errorf("%w: ...", sentinel, ...) to attach runtime context (type names, byte counts, etc.) without losing the sentinel identity.
Functions ¶
func BrandName ¶
BrandName returns the name of the brand if it implements BrandNamer, otherwise returns the type name of the brand.
Example ¶
fmt.Println(BrandName[testUserBrand]())
Output: User
Example (Unnamed) ¶
type MyBrand struct{}
fmt.Println(BrandName[MyBrand]())
Output: id.MyBrand
func MustValidateID ¶ added in v0.3.1
func MustValidateID[B any, V comparable](id ID[B, V])
MustValidateID is like ValidateID but panics if the ID is zero. Use for init-time validation or when a zero ID is a programming error.
func ValidateID ¶
func ValidateID[B any, V comparable](id ID[B, V]) error
ValidateID validates that the given ID is not zero. Returns ErrInvalidID if the ID is zero.
Example:
type UserBrand struct{}
func (UserBrand) Name() string { return "User" }
func main() {
userID := NewID[UserBrand]("user-123")
if err := ValidateID(userID); err != nil {
log.Fatal(err)
}
}
Example ¶
userID := NewID[testUserBrand]("user-123")
if err := ValidateID(userID); err != nil {
fmt.Println(err)
}
Example (Zero) ¶
var emptyUserID ID[testUserBrand, string]
if err := ValidateID(emptyUserID); err != nil {
fmt.Println(err)
}
Output: id: invalid: User: empty
func ValidateIDWithValue ¶
func ValidateIDWithValue[B any, V comparable]( id ID[B, V], validate func(V) error, ) error
ValidateIDWithValue validates that the ID is not zero and optionally validates the value using the provided validator function.
Example ¶
userID := NewID[testUserBrand]("ab")
err := ValidateIDWithValue(userID, func(v string) error {
if len(v) < 3 {
return fmt.Errorf("too short: got %d chars", len(v))
}
return nil
})
fmt.Println(err)
Output: id: invalid: User: too short: got 2 chars
Types ¶
type BrandNamer ¶
type BrandNamer interface {
Name() string
}
BrandNamer is an optional interface that brand types can implement to provide a human-readable name for debugging and logging.
type ID ¶
type ID[B any, V comparable] struct { // contains filtered or unexported fields }
ID is a branded, strongly-typed identifier that prevents mixing different entity IDs. B is the brand (phantom type for distinctness), V is the value type.
The zero value represents an unset/empty ID and serializes to null in JSON.
func FromPtr ¶
func FromPtr[B any, V comparable](p *ID[B, V]) ID[B, V]
FromPtr dereferences a pointer-to-ID, returning the zero value if the pointer is nil.
Example ¶
type UserBrand struct{}
// With non-nil pointer
id := NewID[UserBrand]("user-123")
fmt.Println(FromPtr(id.Ptr()).Get())
// With nil pointer
var nilPtr *ID[UserBrand, string]
fmt.Println(FromPtr(nilPtr).IsZero())
Output: user-123 true
func NewID ¶
func NewID[B any, V comparable](v V) ID[B, V]
NewID creates a new branded identifier from the given value.
Example ¶
type UserBrand struct{}
userID := NewID[UserBrand]("user-123")
fmt.Println(userID.Get())
Output: user-123
func (ID[B, V]) Compare ¶
Compare returns -1 if id < other, 0 if equal, 1 if id > other. Returns ErrNotOrdered if V is not an ordered type.
Example ¶
type OrderBrand struct{}
id1 := NewID[OrderBrand, int64](100)
id2 := NewID[OrderBrand, int64](200)
id3 := NewID[OrderBrand, int64](100)
cmp, _ := id1.Compare(id2)
fmt.Println(cmp)
cmp, _ = id2.Compare(id1)
fmt.Println(cmp)
cmp, _ = id1.Compare(id3)
fmt.Println(cmp)
Output: -1 1 0
func (ID[B, V]) Equal ¶
Equal returns true if this ID equals the other ID. Both IDs must have the same brand and value type.
Example ¶
type UserBrand struct{}
id1 := NewID[UserBrand]("user-123")
id2 := NewID[UserBrand]("user-123")
id3 := NewID[UserBrand]("user-456")
fmt.Println(id1.Equal(id2))
fmt.Println(id1.Equal(id3))
Output: true false
func (ID[B, V]) Format ¶
Format implements fmt.Formatter for custom formatting. Supports %s (string), %d (decimal), %v (default), %#v (GoString), %q (quoted).
Writes directly to fmt.State via io.WriteString to avoid allocations from string concatenation and fmt.Fprint's any boxing.
func (ID[B, V]) GoString ¶
GoString implements fmt.GoStringer for debugging. Returns a Go-syntax-like representation, e.g., id.User("abc123").
func (ID[B, V]) IsZero ¶
IsZero returns true if the ID has its zero value.
Example ¶
type UserBrand struct{}
id := NewID[UserBrand]("user-123")
var zeroID ID[UserBrand, string]
fmt.Println(id.IsZero())
fmt.Println(zeroID.IsZero())
Output: false true
func (ID[B, V]) MarshalBinary ¶
MarshalBinary implements encoding.BinaryMarshaler for binary encoding.
func (ID[B, V]) MarshalJSON ¶
MarshalJSON implements json.Marshaler for proper null handling. String-based IDs serialize as JSON strings, numeric IDs as JSON numbers. Zero values serialize to JSON null.
func (ID[B, V]) MarshalText ¶
MarshalText implements encoding.TextMarshaler for text-based encoding (e.g., XML, TOML). For JSON, prefer the json.Marshaler implementation which handles null properly.
func (ID[B, V]) Or ¶
Or returns the ID if not zero, otherwise returns the provided default.
Example ¶
type UserBrand struct{}
id := NewID[UserBrand]("user-123")
defaultID := NewID[UserBrand]("unknown")
fmt.Println(id.Or(defaultID).Get())
var zeroID ID[UserBrand, string]
fmt.Println(zeroID.Or(defaultID).Get())
Output: user-123 unknown
func (ID[B, V]) Ptr ¶
Ptr returns a pointer to the ID. Useful for optional ID fields in API payloads.
Example ¶
type UserBrand struct{}
id := NewID[UserBrand]("user-123")
p := id.Ptr()
fmt.Println(p.Get())
Output: user-123
func (*ID[B, V]) Reset ¶
func (id *ID[B, V]) Reset()
Reset sets the ID to its zero value.
Example ¶
type UserBrand struct{}
id := NewID[UserBrand]("user-123")
id.Reset()
fmt.Println(id.IsZero())
Output: true
func (*ID[B, V]) Scan ¶
Scan implements sql.Scanner for database deserialization. Supports string, []byte, int64, int, float64, and nil sources based on the underlying value type V.
func (ID[B, V]) String ¶
String returns a string representation of the ID. If the brand type implements BrandNamer, the format is "Brand:value" (e.g., "User:abc123"). Otherwise, returns just the value (e.g., "abc123").
Example ¶
type OrderBrand struct{}
orderID := NewID[OrderBrand, int64](12345)
fmt.Println(orderID.String())
Output: 12345
Example (Named) ¶
userID := NewID[testUserBrand]("abc123")
fmt.Println(userID)
Output: User:abc123
Example (Unnamed) ¶
type AnonBrand struct{}
id := NewID[AnonBrand]("abc123")
fmt.Println(id)
Output: abc123
func (*ID[B, V]) UnmarshalBinary ¶
UnmarshalBinary implements encoding.BinaryUnmarshaler for binary decoding.
func (*ID[B, V]) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler for JSON deserialization. Supports null, strings, and numeric values based on the underlying type V.
func (*ID[B, V]) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler for text-based decoding (e.g., XML, TOML).