id

package module
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-branded-id

Go Version CI Go Reference GitHub stars Documentation

Branded, strongly-typed identifiers for Go. Phantom types prevent mixing different entity IDs at compile time. Zero-allocation. Stdlib-only. Full serialization.

Documentation · Quick Start · API Reference

Why?

In Go, string and int64 provide no compile-time safety against mixing IDs:

// skip-validate: illustrative snippet mixing decls and statements
func GetUser(id string) error { return nil }
func GetOrder(id string) error { return nil }

GetOrder(userID) // Compiles. Silent bug.

With branded IDs, the compiler catches it:

// skip-validate: illustrative snippet mixing decls and statements
type UserBrand struct{}
type OrderBrand struct{}

type UserID = id.ID[UserBrand, string]
type OrderID = id.ID[OrderBrand, string]

func GetUser(id UserID) error   { return nil }
func GetOrder(id OrderID) error { return nil }

GetOrder(userID) // COMPILE ERROR: cannot use UserID as OrderID

The brand types (UserBrand, OrderBrand) are empty structs that exist only as phantom type parameters. They add zero runtime cost — the underlying value is still just a string or int64.

Installation

Prerequisite: Go 1.27+

go get github.com/larsartmann/go-branded-id

Quick Start

package main

import (
    "fmt"

    "github.com/larsartmann/go-branded-id"
)

type UserBrand struct{}

func (UserBrand) Name() string { return "User" }

type UserID = id.ID[UserBrand, string]

func main() {
    userID := id.NewID[UserBrand]("user-123")
    other  := id.NewID[UserBrand]("user-123")

    fmt.Println(userID)              // User:user-123  (named brand shows prefix)
    fmt.Println(userID.Equal(other)) // true
    fmt.Println(userID.Get())        // user-123      (raw value for programmatic use)

    var empty UserID
    fmt.Println(empty.IsZero())      // true

    // Provide a default for zero values
    fmt.Println(empty.Or(id.NewID[UserBrand]("unknown")).Get()) // unknown
}

Features

Feature Description
Compile-time type safety Phantom types prevent mixing UserID with OrderID at the compiler level
Zero allocations Core operations (NewID, Get, Equal, Compare, IsZero) allocate nothing
Stdlib-only No third-party dependencies. Uses only the Go standard library
Full serialization JSON, SQL, Text (XML/TOML), Binary, Gob — all implemented
Named brands Optional Name() method enables "User:abc123" display strings and brand-aware validation
Any comparable type ID[Brand, V comparable] works with strings, ints, and any comparable type
Zero value semantics Zero value means "unset" — serializes to null in JSON, nil in SQL
SQL scanner/valuer Scan accepts all driver types; Value returns the correct type
brandid-lint linter linter/ flags brand types missing Name() (rule BD001) and, opt-in via -rules BD003, primitive-typed ID params/fields that should become branded types; BuildFlow provider and CLI included

Named Brand Types

Adding a Name() method to your brand type enables debug-visible IDs, brand-aware validation errors, and runtime introspection:

// skip-validate: illustrative snippet mixing decls and statements
type UserBrand struct{}
func (UserBrand) Name() string { return "User" }

userID := id.NewID[UserBrand]("abc123")
fmt.Println(userID)               // User:abc123
fmt.Printf("%#v\n", userID)       // id.User(abc123)

var empty ID[UserBrand, string]
fmt.Println(id.ValidateID(empty)) // id: invalid: User: empty

fmt.Println(id.BrandName[UserBrand]()) // User

IDs without Name() work exactly as before — String() returns just the value.

When NOT to brand

Branding is the default for anything that crosses a package boundary, but a plain defined string is the RIGHT answer when one of these holds:

Situation Why the brand buys nothing
encoding/xml round-trips the field The XML decoder constructs values reflectively; a brand forces custom marshalers for zero type-safety gain
Untyped-constant compares are the local idiom (enum slugs) A closed constant set keyed by switch value == SlugX comparisons would need .Get() ceremony at every site
The value is registry text compared against DB-read-back strings Migration ordinals and similar registry rows compare raw-to-raw; the comparison seam is the only operation
The state is ephemeral process state In-memory session/lesson keys that are never persisted and never cross-referenced gain nothing from compile-time separation — brand them when they start crossing boundaries

Rule of thumb from a 142-site migration: brand when an ID KIND could be confused with ANOTHER ID KIND or a plain string at a boundary (wire DTOs, HTTP path params, event payloads); keep defined strings at string-native seams. When in doubt, brand — NewXFrom at the parse point is one line.

Error Handling

All ID operations return sentinel errors that you can match with errors.Is:

// skip-validate: illustrative snippet mixing decls and statements
if err := id.ValidateID(userID); err != nil {
    if errors.Is(err, id.ErrInvalidID) {
        log.Println("ID is zero:", err)
    }
}

_, err := floatID.Compare(otherFloatID)
if errors.Is(err, id.ErrNotOrdered) {
    log.Println("type doesn't support ordering")
}

err = sqlID.Scan(driverValue)
if errors.Is(err, id.ErrCannotScan) {
    log.Println("incompatible SQL source type:", err)
}

Available sentinels:

Sentinel When it fires
ErrInvalidID ValidateID called on a zero ID
ErrNotOrdered Compare called on a non-ordered type (e.g. float)
ErrUnsupportedType Serialization format doesn't support value type V
ErrCannotScan SQL Scan source type doesn't match target V
ErrInsufficientData Binary data too short to decode
ErrMarshal A marshaler (JSON, binary, SQL text) returned error
ErrUnmarshal An unmarshaler (JSON, text, binary) returned error
ErrNilReceiver Method called on nil pointer receiver
ErrInternal Defensive: unreachable type assertion (never fires)

Supported Value Types

The generic type is ID[Brand, V comparable] — any comparable type works as V.

Full serialization support (JSON, SQL, Text, Binary, Gob): string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64.

Other comparable types (structs, arrays, etc.) work for core operations (Get, Equal, IsZero, Reset) but lack specialized serialization.

Serialization

All standard Go interfaces are implemented. Serialization always uses the raw value (no brand prefix):

// JSON — zero values serialize to null
data, _ := json.Marshal(id.NewID[UserBrand]("user-123"))
fmt.Println(string(data)) // "user-123"

var empty UserID
data, _ = json.Marshal(empty)
fmt.Println(string(data)) // null

// SQL — works with database/sql directly
var userID UserID
row.Scan(&userID)
db.Exec("INSERT INTO users (id) VALUES (?)", userID)

Two wire-shape traps worth pinning:

  • Zero encodes null, not "" — a branded field converted from a plain string changes its zero JSON encoding from "" to null. Tagged wire fields that mean absence at zero need omitzero (encoding/json/v2); omitempty never drops it (a struct is never "empty") and does not drop zero numerics under json/v2 either.
  • Zero String() delegates to the value type — for struct-ish value types (e.g. a ULID-backed ID from go-cqrs-lite) the zero ID's String() is the value type's zero rendering (the all-zero ULID string), NOT "". Keep any zero→empty display mapping explicit at templ/log seams.

API Reference

Method Description
NewID[Brand](value) Create a new ID (type inferred for strings)
Get() V Returns the underlying value
IsZero() bool True if ID has its zero value
Equal(other ID) bool True if IDs are equal
Compare(other ID) (int, error) -1, 0, or 1 for ordered types
Or(default ID) ID Returns self if not zero, otherwise default
String() string "Brand:value" if named, else value only
Ptr() *ID / FromPtr(*ID) ID For optional fields

Brand utilities: BrandName[B](), ValidateID(id), ValidateIDWithValue(id, fn), MustValidateID(id)

Full API: pkg.go.dev

Performance

Stdlib-only, allocation-conscious (benchmarked on Go 1.26.4):

Operation Latency Allocations
NewID ~0.4 ns 0
Get ~1 ns 0
Equal ~0.3 ns 0
IsZero ~1.4 ns 0
String (no brand) ~5 ns 0
MarshalJSON ~200 ns 3

Core operations are zero-allocation. Named-brand String() requires one allocation for the "Brand:value" concatenation.

Contributing

Contributions are welcome. Ensure all tests pass and lint is clean:

go test ./... -race
golangci-lint run

License

MIT — Copyright (c) 2026 Lars Artmann. See LICENSE.

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

Examples

Constants

This section is empty.

Variables

View Source
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

func BrandName[B any]() string

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

func (id ID[B, V]) Compare(other ID[B, V]) (int, error)

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

func (id ID[B, V]) Equal(other ID[B, V]) bool

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

func (id ID[B, V]) Format(f fmt.State, verb rune)

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]) Get

func (id ID[B, V]) Get() V

Get returns the underlying value.

func (ID[B, V]) GoString

func (id ID[B, V]) GoString() string

GoString implements fmt.GoStringer for debugging. Returns a Go-syntax-like representation, e.g., id.User("abc123").

func (*ID[B, V]) GobDecode

func (id *ID[B, V]) GobDecode(data []byte) error

GobDecode implements gob.GobDecoder for Go-specific decoding.

func (ID[B, V]) GobEncode

func (id ID[B, V]) GobEncode() ([]byte, error)

GobEncode implements gob.GobEncoder for Go-specific encoding.

func (ID[B, V]) IsZero

func (id ID[B, V]) IsZero() bool

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

func (id ID[B, V]) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler for binary encoding.

func (ID[B, V]) MarshalJSON

func (id ID[B, V]) MarshalJSON() ([]byte, error)

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

func (id ID[B, V]) MarshalText() ([]byte, error)

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

func (id ID[B, V]) Or(defaultValue ID[B, V]) ID[B, V]

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

func (id ID[B, V]) Ptr() *ID[B, V]

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

func (id *ID[B, V]) Scan(src any) error

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

func (id ID[B, V]) String() 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

func (id *ID[B, V]) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler for binary decoding.

func (*ID[B, V]) UnmarshalJSON

func (id *ID[B, V]) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for JSON deserialization. Supports null, strings, and numeric values based on the underlying type V.

func (*ID[B, V]) UnmarshalText

func (id *ID[B, V]) UnmarshalText(data []byte) error

UnmarshalText implements encoding.TextUnmarshaler for text-based decoding (e.g., XML, TOML).

func (ID[B, V]) Value

func (id ID[B, V]) Value() (driver.Value, error)

Value implements driver.Valuer for database serialization. Returns nil for zero values, otherwise the underlying value.

Directories

Path Synopsis
linter module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址