types

package module
v1.0.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 14 Imported by: 4 modules, 3 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-types

Go Reference Go Report Card Go Go version license

Go types for the data that business documents are made of: money amounts and currencies, dates, IBANs and BICs, VAT IDs, country and language codes, email addresses and messages, and UUIDs. Each type parses the many ways people and other systems write a value, normalizes it to one canonical form, validates it, and round-trips through database/sql, encoding/json and encoding/xml. Optional values have Nullable variants that map to SQL NULL and JSON null.

go get github.com/domonda/go-types

Requires Go 1.26 or later.

Quick start

package main

import (
	"fmt"

	"github.com/domonda/go-types/bank"
	"github.com/domonda/go-types/date"
	"github.com/domonda/go-types/language"
	"github.com/domonda/go-types/money"
	"github.com/domonda/go-types/vat"
)

func main() {
	// Normalize identifiers as they appear on invoices
	vatID, err := vat.ID("atu 1022 3006").Normalized()
	fmt.Println(vatID, err)

	iban, err := bank.IBAN("DE89 3704 0044 0532 0130 00").Normalized()
	fmt.Println(iban, err)

	// Dots are day first, slashes month first unless a language hint says otherwise
	d, err := date.Normalize("05.06.2024")
	fmt.Println(d, err)
	d, err = date.Normalize("05/06/2024", language.EN)
	fmt.Println(d, err)

	// Exact money amounts with locale-aware parsing
	amount, err := money.ParseDecimalAmount("1.234,50")
	fmt.Println(amount, err)
	currency, err := money.Currency("€").Normalized()
	fmt.Println(currency, err)

	// Integer cents split without losing or inventing a cent
	fmt.Println(money.CentAmount(1000).SplitEqually(3))

	// Output:
	// ATU10223006 <nil>
	// DE89370400440532013000 <nil>
	// 2024-06-05 <nil>
	// 2024-05-06 <nil>
	// 1234.50 <nil>
	// EUR <nil>
	// [3.33 3.33 3.34]
}

New here? The tutorial builds an invoice record from raw strings to validated JSON and SQL values step by step.

Packages

Package What it gives you
types (root) Set[T], the Validator/Validatable interfaces with Validate and DeepValidate, Normalizable, LenString, KeyMutex, Finder, pointer and iterator helpers
account Alphanumeric account numbers with SQL, JSON and XML support
bank IBAN and BIC validation and normalization, finders for document text, CAMT.053 XML structs
charset BOM detection, UTF-16 and UTF-32, legacy charsets by IANA or MIME label
country ISO 3166-1 alpha-2 country codes, alternative spellings, EU membership
date ISO 8601 Date, YearMonth, YearQuarter, lenient locale-aware parsing, period ranges
email Lenient address parsing, address lists and sets, MIME and TNEF message parsing and building
float Locale-aware float parsing and formatting, decimal rounding, a JSON-tolerant float
language ISO 639-1 language codes from BCP 47, ISO 639-2/3 and locale identifiers
mapset Set algebra on map[K]struct{} and map[K]bool, mirroring the proposed container/mapset
money Amount (float64), CentAmount (int64 cents), DecimalAmount (exact fixed-point), ISO 4217 currencies, rates
notnull Never-null SQL/JSON wrappers: nil slices become '{}' and []
nullable Nullable wrappers that map the zero value to SQL NULL and JSON null, generic Type[T]
queue Unbounded goroutine-safe FIFO queue consumed through a channel
set Helpers for map[T]struct{} sets (prefer mapset for new code)
strfmt Reflection-driven scanning and formatting of values with locale presets
strutil Trimming, rune filtering, transliteration, file names, domain extraction, StringSet
strutil/stringfrom Render pointers and optional values as strings with a text for nil
uu UUID ID, NullableID, IDSlice, IDSet, v7 by default, context-injectable generation
vat European VAT IDs with per-country format and checksum validation

Every package README is the complete reference for its package: all exported types and functions, how each value is written to and read from SQL and JSON, the gotchas, and runnable examples. The same API is on pkg.go.dev.

Documentation

The docs index lists everything. By what you need:

Conventions shared by all packages

  • Identifier types like country.Code, vat.ID, bank.IBAN and uu.ID have an invalid zero value, and their NullableX variant uses that zero value as SQL NULL and JSON null. Number types like money.Amount, where zero is a valid value, use the generic nullable.Type[T] instead. See null conventions.
  • Valid() bool and Validate() error accept the input that Normalized() accepts, so country.Code("de").Valid() and vat.ID("atu 1022 3006").Valid() are true. ValidAndNormalized() reports whether a value is already in canonical form. See validation and normalization.
  • Reading and writing trim, and uppercase IBAN, BIC, VAT, currency and year-quarter. Country codes, language codes, email addresses and year-months are only trimmed. Value() writes an invalid value back. date.Date on SQL still fully normalizes. fmt prints the stored value, see Reading and writing values. How each type is written to and read from SQL, JSON and XML, including its zero and null values, is in the Serialization section of its package README.
  • types.Validate and types.DeepValidate work with any type that implements Validate() error or Valid() bool, including your own.

Reading and writing values

SQL, JSON, XML and text only prettify a value. They trim surrounding whitespace, and uppercase letters where the type is written in upper case: bank.IBAN, bank.BIC, vat.ID, money.Currency, date.YearQuarter. country.Code, language.Code, email.Address and date.YearMonth are only trimmed, so "Deutschland" stays "Deutschland" and "EN" stays "EN". An invalid value is written back after that prettification. Value does not refuse it. Normalized() is unchanged and is what ScanString(s, true) stores. Printing shows what is stored.

date.Date is the exception on SQL. Scan and Value fully normalize, because a database date is not free text. A time.Time from the driver is stored with OfTime, which is already YYYY-MM-DD. JSON and XML only trim.

Methods per format
Format Read Write
SQL, database/sql Scan Value
JSON, encoding/json UnmarshalJSON MarshalJSON
XML, encoding/xml UnmarshalXML, UnmarshalXMLAttr MarshalText, MarshalXMLAttr
Text, strfmt and CSV ScanString MarshalText
JSON object keys of a map as given as given
fmt, templates, logs as stored
Reading
Input Scan, JSON, XML, ScanString(s, false) ScanString(s, true)
"DE" "DE" "DE"
" de " "de" "DE"
"Deutschland" "Deutschland" "DE"
"XX" "XX", no error error
"", " " "" Code: error, NullableCode: null
SQL NULL ""
JSON null Code: unchanged, NullableCode: ""
JSON number, SQL integer error

For date.Date and date.NullableDate, SQL Scan and Value treat the zero dates 0001-01-01 and 0000-00-00, and spellings of them like 01.01.0001, as blank. JSON and XML only trim, so those spellings stay. A time.Time from the driver is stored with OfTime, and the zero time.Time as "". date.YearMonth and date.YearQuarter read a time.Time as its month or quarter the same way, and keep a zero value such as "0001-01" or "0001-Q1" when it is already text.

Reading never fails because of the text itself. An invalid value is kept after prettification, so one bad row doesn't fail a whole query or JSON document, and types.DeepValidate reports it together with its field path.

Writing
Value in Go Value (SQL) MarshalJSON MarshalText, XML fmt, String
"DE" DE "DE" DE DE
"de", converted in Go de "de" de de
"XX" XX "XX" XX XX
"" NULL Code: "", NullableCode: null empty empty

fmt, templates and String show the value as it is stored. Normalized() is the canonical spelling, and it is not applied while reading or writing.

XML writes <country>DE</country> for an element and country="DE" for an attribute field. A nil *country.Code attribute field is left out, with or without omitempty. A nil pointer ,chardata field still makes encoding/xml panic, like a nil *time.Time, because encoding/xml calls MarshalText through the nil pointer and has no hook to skip it; use a non-pointer ,chardata field.

Differences between types
Types Difference
country.Code, money.Currency, language.Code String() is generated by go-enum and returns the stored value
date.YearMonth, date.YearQuarter and their nullable types String() returns the stored value
vat.ID, bank.IBAN, bank.BIC, date.Date, email.Address no String() method, fmt prints the stored value
NullableX variants blank is null; StringOr(alt) returns alt only for null; ScanString also reads NULL, null and nil as null
language.Code no nullable variant, its "" is null
email.AddressList, email.NullableAddressList the list string is trimmed; addresses are not parsed or lowercased; Value does not reject an invalid list; normalize with Normalized()
email.AddressSet, types.Set[T] keys as stored, so {"a@x.com", "A@x.com"} and a padded key stay distinct; AddressSet writes a PostgreSQL text[] array in SQL, a sorted array as JSON, and an address list as text and XML; MarshalText refuses a key that would not read back as one list entry; normalize with Normalized() or NormalizedAddressList()
Scan and UnmarshalJSON of the email collections read a PostgreSQL array, a JSON array, a JSON object with the addresses as keys, a JSON string and a plain address list
money.CurrencyAmount, money.CurrencyDecimalAmount currency trimmed and uppercased in Value and JSON, as stored in String
notnull.TrimmedString, nullable.TrimmedString trimmed when read and in String
notnull.TrimmedString, nullable.TrimmedString, account.Number, account.NullableNumber encoding/json reads the keys of a map of them trimmed, so " a" and "a" merge into one key

A set writes its elements as given because normalizing could merge two of them, and the set would come back with fewer elements than it was written with. For the same reason the keys of a map[country.Code]V are read and written as given in JSON. The normalizing types have no UnmarshalText for that reason: encoding/json decodes a map key of a type with UnmarshalText through it, and in Go 1.26 through its UnmarshalJSON. The trimming string types and account.Number keep UnmarshalText, because trimming is what they are for and flag.TextVar and other text decoders need it, so their map keys are trimmed.

Design decisions

These rules decide how every type behaves, and how an inconsistency between types gets resolved. Types that don't follow a rule yet are tracked in TODOS.md.

  • Be generous in accepting input, and do not rewrite stored data. Normalized() and Validate() accept every common spelling: country.Code("de"), vat.ID("atu 1022 3006") and money.Currency("€") are valid input. Reading and writing do not apply that canonical form. They only trim, and uppercase where the type is written in upper case, so a value already in the database is not replaced by a stricter spelling. date.Date on SQL is the exception, and uu.ID stays fully canonical. Call Normalized() when a comparison or a map key needs the canonical form. The email types have an extra ASCII() for message headers.
  • Show what is stored. fmt, templates and String print a value as it is stored, never normalized, so a log can't show a non-canonical or invalid value as if it were the canonical one.
  • Collections keep their elements as given. types.Set and email.AddressSet read and write their keys as stored, because normalizing could merge two elements, and a set would read back with fewer elements than it was written with. An address list trims the list string and does not parse or lowercase the addresses. Value does not reject an invalid list. Normalizing them is an explicit call.
  • Empty input is null. For a nullable type, an empty or whitespace-only string from SQL, JSON or text is null, because an empty CSV cell or text column means "no value". A non-nullable type reads it as its empty value, which is invalid, and writes that as SQL NULL, so a NOT NULL column rejects it.
  • Fail loudly instead of guessing. Input that contradicts itself, or whose meaning depends on something the package can't know, is an error instead of a silently wrong value. A number with an ordinal suffix is never read as the month, so "13 1st 2024" is an error, and strfmt rejects a time zone abbreviation whose offset is unknown on the machine instead of reading the time as UTC. A documented default is no guess: an ambiguous date like 05.06.2024 is day first with dots, and 05/06/2024 is month first with slashes unless a language hint says otherwise.
  • Errors are created with github.com/domonda/go-errs (errs.New, errs.Errorf) instead of errors.New and fmt.Errorf.

Development

go test ./...          # all tests
./run-go-enum.sh       # regenerate Enums()/EnumStrings() after adding a code
./run-gosec.sh         # static security analysis

go-enum and gosec are pinned as tool dependencies in tools/go.mod, so the main module does not depend on them. CI builds, vets, checks that the generated enum methods are up to date and runs the tests with the race detector on every pull request.

Status

No version has been tagged yet. CHANGELOG.md lists every change, including the breaking ones, and TODOS.md lists what is left before v1.0.0.

License

MIT, see LICENSE. The uu package is derived from github.com/satori/go.uuid.

Documentation

Overview

Package types is the root of the github.com/domonda/go-types module: a collection of Go packages providing enhanced type definitions, validation, and utility functions for common data and domain types.

The root package itself provides foundational utilities used by the rest of the module:

Subpackages

Domain value types with validation, normalization, and SQL/JSON integration:

Wrappers for SQL/JSON null semantics:

String and numeric utilities:

Generic collection helpers:

Most types in this module follow consistent conventions: a non-nullable type (e.g. github.com/domonda/go-types/money.Currency) where the empty value is invalid, paired with a NullableX variant where the empty value is a valid NULL representation that round-trips through SQL and JSON. Some NullableX types, like github.com/domonda/go-types/money.NullableAmount, are aliases of github.com/domonda/go-types/nullable.Type instead, because the zero value of the wrapped type is valid. SQL is supported via database/sql.Scanner and database/sql/driver.Valuer. JSON works through encoding/json, natively for string based types or via encoding/json.Marshaler and encoding.TextMarshaler methods. Many types also provide a JSONSchema method compatible with github.com/invopop/jsonschema.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CanMarshalJSON

func CanMarshalJSON(t reflect.Type) bool

CanMarshalJSON reports whether encoding/json.Marshal can encode a value of type t purely based on t's static structure. It returns true when:

  • t is the empty interface [any] or any other interface type,
  • t implements json.Marshaler or encoding.TextMarshaler (directly or via its pointer receiver),
  • t is a primitive kind that encoding/json accepts: bool, any integer or unsigned integer kind, float32/float64, or string,
  • t is an array, slice, or struct (field types are not inspected),
  • t is a map whose key kind is supported by encoding/json: string, any integer kind, or a key type that implements encoding.TextMarshaler itself, not only via its pointer type, because map keys are not addressable,
  • t is a pointer to a marshalable element type.

Kinds rejected by encoding/json (complex, chan, func, unsafe.Pointer) return false. The check has false positives, where it returns true but encoding/json fails at runtime:

  • struct field, array and slice element, and map value types are not inspected, so a struct with a chan field or a non-empty []func() passes the check,
  • encoding/json calls a method with a pointer receiver only for addressable values, so a type whose pointer type alone implements json.Marshaler or encoding.TextMarshaler can still fail when marshalled by value,
  • value-dependent failures such as float NaN/Inf are invisible here.

func CompareReflectValue

func CompareReflectValue(a, b reflect.Value) int

CompareReflectValue compares two reflect.Values and returns -1, 0, or +1 like cmp.Compare, so it can be used as the comparison function for slices.SortFunc. Returns 0 if the values are not of the same type or not of an orderable kind, so sorting mixed or non-orderable values does not panic. The resulting order of such values is unspecified, because treating them as equal to each other but not to the values between them breaks the strict weak ordering that slices.SortFunc requires.

The invalid zero reflect.Value, which has no type, is ordered before all valid values.

Orderable kinds are:

  • all integer, unsigned integer, and float kinds (compared by value)
  • strings (compared lexicographically)
  • bool (false < true)
  • complex (compared by real part, then imaginary part)
  • pointer, channel, and unsafe pointer (compared by address)
  • array and slice (compared lexicographically by element, shorter first on tie; []byte uses bytes.Compare)
  • struct (compared lexicographically by field)
  • interface (nil first, then compared by dynamic type name, then by underlying value)

This is used for sorting map keys in DeepValidate.

func DeepValidate

func DeepValidate(v any) []error

DeepValidate recursively validates v and everything reachable from it, returning every validation error encountered.

The traversal:

  • calls Validate on v itself, then on every reachable element, through a pointer to the element if only the pointer type implements Validatable or Validator, like LenString (an element that is not addressable is copied for that, but not v itself: like Validate, v passed by value is validated with the methods of its own type, so a pointer receiver Validate calling DeepValidate(*receiver) does not call itself again; such a nested call has its own cycle detection though, and its errors are reported again by the descent of an outer DeepValidate, so prefer to check only cross-field rules in Validate),
  • follows pointers and interfaces to any depth (nil pointers, interfaces, and funcs stop the descent),
  • recurses into exported struct fields, including the exported fields of unexported embedded structs, slice and array elements, and map values (map keys are not validated, but are sorted with CompareReflectValue so error order is deterministic, apart from among multiple NaN keys),
  • skips unexported struct fields, which cannot be inspected via reflection,
  • does not descend again into a pointer, map, or slice that it is already descending into higher up on the path, so cyclic data is validated once instead of recursing until the stack overflows.

Errors are prefixed with a human-readable path to the offending value, e.g. `struct field Users -> element [1] -> struct field Status: invalid main.Status value: "unknown"`. An error of v itself is returned without a prefix. The prefixed errors wrap the errors returned by Validate, so errors.Is and errors.As see through the path.

Use errors.Join(DeepValidate(v)...) to join the errors into a single error.

func FromPtr

func FromPtr[T any](ptr *T) T

FromPtr returns the dereferenced value of the pointer if it is not nil, otherwise it returns the zero value of the type T. This safely dereferences a pointer without panicking on nil.

func FromPtrOr

func FromPtrOr[T any](ptr *T, defaultValue T) T

FromPtrOr returns the dereferenced value of the pointer if it is not nil, otherwise it returns the passed defaultValue. This provides a safe way to dereference a pointer with a fallback value.

func ReduceSet

func ReduceSet[S ~map[T]struct{}, T cmp.Ordered, R any](set S, reduceFunc func(last R, val T) R) (result R)

ReduceSet applies a reduction function to all values in the set and returns the result. The reduceFunc is called for each value in the set, with the accumulated result and the current value. The first call gets the zero value of R as accumulated result. The values are passed in undefined map iteration order, so only an order independent reduceFunc gives a deterministic result.

func ReduceSlice

func ReduceSlice[S ~[]T, T cmp.Ordered, R any](slice S, reduceFunc func(last R, val T) R) (result R)

ReduceSlice applies a reduction function to all values in the slice and returns the result. The reduceFunc is called for each value in the slice, with the accumulated result and the current value. The first call gets the zero value of R as accumulated result.

func Seq2NilError

func Seq2NilError[K any](seq iter.Seq[K]) iter.Seq2[K, error]

Seq2NilError converts a sequence of values to a sequence of key-value pairs with the passed sequence values as keys and nil errors as values. This is useful for converting a value sequence to a key-error sequence where all errors are nil (indicating success).

func SetToRandomizedSlice

func SetToRandomizedSlice[S ~map[T]struct{}, T cmp.Ordered](set S) []T

SetToRandomizedSlice converts a set to a slice with values in map iteration order, which is unspecified but not a random shuffle. Returns nil for an empty or nil set.

func SetToSortedSlice

func SetToSortedSlice[S ~map[T]struct{}, T cmp.Ordered](set S) []T

SetToSortedSlice converts a set to a slice with values in sorted order. Returns nil for an empty or nil set.

func SliceContainsAll

func SliceContainsAll[T comparable](outer []T, inner ...T) bool

SliceContainsAll returns true if outer contains all elements of inner. It returns false if any element in inner is not found in outer. Duplicate elements in inner don't have to occur multiple times in outer, so inner can have more elements than outer.

func SliceContainsAny

func SliceContainsAny[T comparable](outer []T, inner ...T) bool

SliceContainsAny returns true if outer contains any element of inner. It returns true as soon as the first element from inner is found in outer, false if none of the elements in inner are found in outer.

func TryValidate

func TryValidate(v any) (implemented bool, err error)

TryValidate returns true and an error if v implements Validatable or Validator and the methods Validatable.Validate() or Validator.Valid() indicate an invalid value. If v implements both interfaces, only Validatable.Validate() is called. The error from Validatable.Validate() is returned unchanged. If Validator.Valid() is false, which can't tell why v is invalid, an error naming the type and value of v is returned, like `invalid main.Status value: "unknown"`. Any non-nil error means v is invalid. If v does not implement Validatable or Validator then false and nil will be returned. If v is a nil pointer to a type implementing the method with a value receiver, which can't be called without a value, then true and nil are returned, like DeepValidate skips nil pointers. A method with a pointer receiver is called with the nil pointer, so it can handle nil itself. If v is a nil func like ValidatorFunc(nil), whose method would call the nil func, then true and nil are returned, like DeepValidate skips nil funcs. The same is returned if v embeds a nil pointer or interface that its method is promoted from, see Validate. The boolean result reports whether v implements Validatable or Validator.

func ValidOr

func ValidOr[T Validator](val, def T) T

ValidOr returns val if val.Valid() is true, else def, which is returned without being validated. The method is called directly, so unlike Validate, which skips a value whose method can't be called, ValidOr panics for a nil ValidatorFunc, a nil Validator interface value, or a nil pointer to a type with a value receiver Valid method.

func Validate

func Validate(v any) error

Validate returns an error if v implements Validatable or Validator and the methods Validatable.Validate() or Validator.Valid() indicate an invalid value. If v implements both interfaces, only Validatable.Validate() is called. The error from Validatable.Validate() is returned unchanged. If Validator.Valid() is false, which can't tell why v is invalid, an error naming the type and value of v is returned, like `invalid main.Status value: "unknown"`. Any non-nil error means v is invalid. If v does not implement Validatable or Validator then nil will be returned. If v is a nil pointer to a type implementing the method with a value receiver, which can't be called without a value, then nil is returned, like DeepValidate skips nil pointers. A method with a pointer receiver is called with the nil pointer, so it can handle nil itself. If v is a nil func like ValidatorFunc(nil), whose method would call the nil func, then nil is returned, like DeepValidate skips nil funcs. If v embeds a nil pointer or interface that its method is promoted from, like struct{ *T } with a nil *T and a value receiver on T, or struct{ Validatable } with a nil Validatable, then nil is returned too, because the method can't be called without the embedded value. A panic in a method that v declares itself is passed on, also if v embeds a nil pointer or interface.

func ValidatedOr

func ValidatedOr[T Validatable](val, def T) T

ValidatedOr returns val if val.Validate() returns nil, else def, which is returned without being validated. The error of val.Validate() is discarded, use Validate to get it. The method is called directly, so unlike Validate, which skips a value whose method can't be called, ValidatedOr panics for a nil ValidatableFunc, a nil Validatable interface value, or a nil pointer to a type with a value receiver Validate method.

func Yield

func Yield[V any](value V) iter.Seq[V]

Yield returns an iterator that yields a single value. This is useful for converting a single value into an iterator sequence.

func Yield2

func Yield2[K, V any](key K, value V) iter.Seq2[K, V]

Yield2 returns an iterator that yields a single key-value pair. This is useful for converting a single key-value pair into an iterator sequence.

func YieldErr

func YieldErr[K any](err error) iter.Seq2[K, error]

YieldErr returns an iterator that yields a single key-value pair with the default value for the key type K and the passed error as the value. This is useful for propagating errors through iterator sequences.

Types

type Finder

type Finder interface {
	// FindAllIndex finds all occurrences of the pattern in str and returns
	// a slice of byte index pairs [start, end) for each match,
	// so str[start:end] is the matched text.
	// The parameter n limits the number of matches returned:
	//   - n < 0: return all matches
	//   - n == 0: return no matches
	//   - n > 0: return at most n matches
	FindAllIndex(str []byte, n int) [][]int
}

Finder defines an interface for finding patterns in byte slices. It provides a method to find all occurrences of a pattern within a string, returning the start and end indices of each match.

type KeyMutex

type KeyMutex[T comparable] struct {
	// contains filtered or unexported fields
}

KeyMutex manages a unique mutex for every locked key. The mutex for a key exists as long as there are any locks waiting to be unlocked. This is equivalent to declaring a mutex variable for every key, except that the key and the number of mutexes are dynamic. Like a sync.Mutex it is not reentrant, locking a key again from the goroutine holding it deadlocks.

func NewKeyMutex

func NewKeyMutex[T comparable]() *KeyMutex[T]

NewKeyMutex returns a new KeyMutex

func (*KeyMutex[T]) IsLocked

func (m *KeyMutex[T]) IsLocked(key T) bool

IsLocked tells whether a key is locked or a Lock call for it is in progress. The result is a snapshot that can change right after the call.

func (*KeyMutex[T]) Lock

func (m *KeyMutex[T]) Lock(key T)

Lock the mutex for a given key. The zero value of KeyMutex is usable, it is initialized by the first Lock call.

func (*KeyMutex[T]) Unlock

func (m *KeyMutex[T]) Unlock(key T)

Unlock the mutex for a given key. It panics if the key is not locked.

type LenString

type LenString struct {
	// contains filtered or unexported fields
}

LenString holds a string together with a minimum and maximum length constraints. It implements validation to ensure the string length falls within the specified bounds. The length is counted in bytes, not runes. All methods have pointer receivers, so a LenString value that is not addressable, like a field of a struct marshalled by value, is encoded by encoding/json as an empty object. LenString implements the encoding.TextUnmarshaler, json.Unmarshaler, and strfmt.Scannable interfaces that will perform length validation.

func MustLenString

func MustLenString(str string, min, max int) LenString

MustLenString returns a LenString or panics on errors from Validate. Use this when you're certain the string meets the length constraints.

func NewLenString

func NewLenString(str string, min, max int) *LenString

NewLenString returns a new LenString without validating it. Use this when you want to create a LenString and validate it separately.

func (*LenString) MarshalJSON

func (s *LenString) MarshalJSON() (text []byte, err error)

MarshalJSON implements the json.Marshaler interface.

func (*LenString) MarshalText

func (s *LenString) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface.

func (*LenString) MaxLen

func (s *LenString) MaxLen() int

MaxLen returns the maximum allowed length for the string.

func (*LenString) MinLen

func (s *LenString) MinLen() int

MinLen returns the minimum allowed length for the string.

func (*LenString) ScanString

func (s *LenString) ScanString(source string, validate bool) error

ScanString tries to parse and assign the passed source string as value of the implementing type.

If validate is true, the source string is checked for validity before it is assigned to the type.

If validate is false and the source string can still be assigned in some non-normalized way it will be assigned without returning an error.

func (*LenString) SetString

func (s *LenString) SetString(str string) error

SetString sets the string value after validating it against the length constraints. Returns an error if the string doesn't meet the length requirements.

func (*LenString) String

func (s *LenString) String() string

String returns the string or "<nil>". String implements the fmt.Stringer interface.

func (*LenString) UnmarshalJSON

func (s *LenString) UnmarshalJSON(text []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. It validates the string length after unmarshaling from JSON and leaves the value unchanged if the length is not valid. JSON null leaves the value unchanged too.

func (*LenString) UnmarshalText

func (s *LenString) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. It validates the text length before setting the string value.

func (*LenString) Validate

func (s *LenString) Validate() error

Validate implements the Validatable interface. It checks that the minimum and maximum lengths are valid and that the string length falls within the specified bounds.

type Normalizable

type Normalizable[T any] interface {
	// Normalized returns the normalized value of type T or an error if normalization fails.
	Normalized() (T, error)
}

Normalizable is a generic interface for types that can be normalized to a standard form. Normalization typically involves converting input data to a consistent, validated format. This interface is commonly implemented by types that handle user input or external data that may come in various formats but need to be standardized.

The Normalized method should:

  • Return the normalized value in its standard form
  • Return an error if the value cannot be normalized
  • Be idempotent (calling Normalized on an already normalized value should return the same result)

type NormalizableValidator

type NormalizableValidator[T any] interface {
	Validator
	Normalizable[T]

	// ValidAndNormalized returns true if the value is both valid and already in normalized form.
	// This is a performance optimization that avoids the need to call both Valid() and Normalized()
	// separately when checking if a value is ready for use.
	ValidAndNormalized() bool
}

NormalizableValidator is a generic interface that combines validation and normalization capabilities. It extends both the Validator interface and Normalizable interface for types that need both validation and normalization functionality.

This interface is particularly useful for types that:

  • Accept input in various formats
  • Need to validate the input before normalization
  • Should provide a quick check for both validity and normalization status

type Set

type Set[T cmp.Ordered] map[T]struct{}

Set represents a collection of unique ordered values. It is implemented as a map[T]struct{} for efficient lookups and memory usage. The type parameter T must be comparable and ordered (implements cmp.Ordered).

func NewSet

func NewSet[T cmp.Ordered](vals ...T) Set[T]

NewSet creates a new Set containing the provided values. Duplicate values are automatically deduplicated.

func (Set[T]) All

func (set Set[T]) All() iter.Seq[T]

All returns an iterator over the values of the set in undefined order. It is valid to call this method on a nil set.

func (Set[T]) Clear

func (set Set[T]) Clear()

Clear removes all values from the set. It is valid to call this method on a nil set.

func (Set[T]) Clone

func (set Set[T]) Clone() Set[T]

Clone returns a new set with the same values, or nil if the set is nil.

func (Set[T]) Contains

func (set Set[T]) Contains(val T) bool

Contains returns true if the set contains the specified value. It is valid to call this method on a nil set.

func (Set[T]) ContainsAll

func (set Set[T]) ContainsAll(seq iter.Seq[T]) bool

ContainsAll returns true if the set contains all values yielded by seq. It returns true for an empty sequence and is valid to call on a nil set.

func (Set[T]) ContainsAny

func (set Set[T]) ContainsAny(vals ...T) bool

ContainsAny returns true if the set contains any of the specified values.

func (Set[T]) ContainsSet

func (set Set[T]) ContainsSet(other Set[T]) bool

ContainsSet returns true if this set contains all values from the other set.

func (Set[T]) Delete

func (set Set[T]) Delete(val T) bool

Delete removes a value from the set and reports whether the set was changed. It is valid to call this method on a nil set.

func (Set[T]) DeleteAll

func (set Set[T]) DeleteAll(seq iter.Seq[T]) bool

DeleteAll removes all values yielded by seq from the set and reports whether the set was changed. It is valid to call this method on a nil set.

func (Set[T]) DeleteFunc

func (set Set[T]) DeleteFunc(del func(T) bool) bool

DeleteFunc removes all values for which del returns true and reports whether the set was changed. It is valid to call this method on a nil set.

func (Set[T]) Difference

func (set Set[T]) Difference(other Set[T]) Set[T]

Difference returns a new set containing the values of this set that are not in the other set.

Note that this is the asymmetric difference as defined by the Go collections proposal. Up to and including go-types v0 pseudo-versions before 2026-08 this method returned the symmetric difference, which is now Set.SymmetricDifference.

func (Set[T]) DifferenceWith

func (set Set[T]) DifferenceWith(other Set[T])

DifferenceWith removes all values of the other set from this set. It is valid to call this method on a nil set.

func (Set[T]) Equal

func (set Set[T]) Equal(other Set[T]) bool

Equal returns true if both sets contain exactly the same values.

func (Set[T]) GetOne

func (set Set[T]) GetOne() T

GetOne returns one element of the set or the default value for T if the set is empty. The element returned is not guaranteed to be any specific element from the set.

func (Set[T]) Insert

func (set Set[T]) Insert(val T) bool

Insert adds val to the set and reports whether the set was changed. It panics if the set is nil and val is not already an element.

func (Set[T]) InsertAll

func (set Set[T]) InsertAll(seq iter.Seq[T]) bool

InsertAll adds all values yielded by seq to the set and reports whether the set was changed. It panics if the set is nil and seq yields a value that is not already an element.

func (Set[T]) Intersection

func (set Set[T]) Intersection(other Set[T]) Set[T]

Intersection returns a new set containing only values that exist in both sets.

func (Set[T]) IntersectionWith

func (set Set[T]) IntersectionWith(other Set[T])

IntersectionWith removes all values from this set that are not also in the other set. It is valid to call this method on a nil set.

func (Set[T]) Intersects

func (set Set[T]) Intersects(other Set[T]) bool

Intersects reports whether this set and the other set have at least one value in common.

func (Set[T]) IsEmpty

func (set Set[T]) IsEmpty() bool

IsEmpty returns true if the set is empty or nil.

func (Set[T]) IsNull

func (set Set[T]) IsNull() bool

IsNull implements the nullable.Nullable interface by returning true if the set is nil.

func (Set[T]) Len

func (set Set[T]) Len() int

Len returns the number of values in the set. Returns zero for a nil set.

func (Set[T]) Map

func (set Set[T]) Map(mapFunc func(T) (T, bool)) Set[T]

Map applies a transformation function to each value in the set and returns a new set containing the results. The mapFunc should return the transformed value and a boolean indicating whether to include the result in the new set. The returned set is never nil, also not for a nil set.

func (Set[T]) MarshalJSON

func (set Set[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler. A nil set is encoded as null, an empty set as [], and any other set as an array of its values in ascending order. Values of a normalizing string type, which implements Normalizable, like money.Currency, are written as stored, without the MarshalJSON method of T that normalizes, because two values like "eur" and "EUR" would be written as the same value and the set would read back with fewer values than it was written with. Other values are written with their own MarshalJSON method.

func (Set[T]) Sorted

func (set Set[T]) Sorted() []T

Sorted returns a slice containing all values in the set, sorted in ascending order. Returns nil for an empty or nil set.

func (Set[T]) String

func (set Set[T]) String() string

String implements the fmt.Stringer interface. Returns a string representation of the set with values in sorted order, formatted with %#v, like [1, 2, 3] or ["a", "b"], and <nil> for a nil set.

func (Set[T]) SymmetricDifference

func (set Set[T]) SymmetricDifference(other Set[T]) Set[T]

SymmetricDifference returns a new set containing the values that exist in either set but not in both.

func (Set[T]) SymmetricDifferenceWith

func (set Set[T]) SymmetricDifferenceWith(other Set[T])

SymmetricDifferenceWith replaces the values of this set with the values that exist in either set but not in both. It panics if this set is nil and the other set has a value that is not already an element.

func (Set[T]) Union

func (set Set[T]) Union(other Set[T]) Set[T]

Union returns a new set containing all values from both this set and the other set.

func (Set[T]) UnionWith

func (set Set[T]) UnionWith(other Set[T])

UnionWith adds all values of the other set to this set. It panics if this set is nil and the other set has a value that is not already an element.

func (*Set[T]) UnmarshalJSON

func (set *Set[T]) UnmarshalJSON(j []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler. It unmarshals a JSON array into the set, removing any duplicates. Values of a normalizing string type, which implements Normalizable, are stored as given, without the UnmarshalJSON method of T that normalizes, so that MarshalJSON and UnmarshalJSON round-trip every set. Other values are read with their own UnmarshalJSON method. It assigns a new set rather than modifying the existing map, so a map shared with another variable is never rewritten. JSON null assigns a nil set and the empty array an allocated empty one, mirroring Set.MarshalJSON. A nil set panics when inserted into, exactly like a nil Go map.

type StaticValidatable

type StaticValidatable struct {
	Err error
}

StaticValidatable implements the Validatable interface for a validation error value. This is useful when you have a pre-computed validation error.

func (StaticValidatable) Validate

func (v StaticValidatable) Validate() error

Validate returns an error if the data of the implementation is not valid.

type StaticValidator

type StaticValidator bool

StaticValidator implements the Validator interface with a bool validity value. This is useful when you have a pre-computed validation result.

func (StaticValidator) Valid

func (valid StaticValidator) Valid() bool

Valid returns if the data of the implementation is valid.

type Validatable

type Validatable interface {
	// Validate returns an error if the data of the implementation is not valid.
	Validate() error
}

Validatable can be implemented by types that can validate their data and return detailed error information. This is more informative than the Validator interface as it provides specific error details.

Any non-nil error means the data is invalid, so the error should describe what is invalid.

func CombinedValidatable

func CombinedValidatable(validatables ...Validatable) Validatable

CombinedValidatable creates a Validatable whose Validate method returns the errors of all the passed validatables Validate methods joined with errors.Join, or nil if none returned an error. Every validatable is called, also after an earlier one failed, see Validatables.Validate. This is equivalent to creating a Validatables slice.

type ValidatableFunc

type ValidatableFunc func() error

ValidatableFunc implements the Validatable interface with a function. This allows you to use a function as a validator that returns detailed errors.

func (ValidatableFunc) Validate

func (f ValidatableFunc) Validate() error

Validate returns an error if the data of the implementation is not valid.

type Validatables

type Validatables []Validatable

Validatables is a slice of Validatable implementations. It implements the Validatable interface itself, returning the errors of all its elements joined.

func (Validatables) Validate

func (v Validatables) Validate() error

Validate calls Validate on every element of v, also after one of them returned an error, and returns all their errors joined with errors.Join, or nil if no element returned an error. errors.Is and errors.As find each of the joined errors. Elements that Validate does not validate are skipped: nil, a nil func, a nil pointer to a type implementing Validatable with a value receiver, and a value whose Validate method is promoted from a nil embedded pointer or interface.

Because an element is called also after an earlier one failed, no element may rely on an earlier one, like a check of a field that relies on an earlier check that the pointer to the struct is not nil. Make such dependent checks one Validatable instead.

type Validator

type Validator interface {
	// Valid returns if the data of the implementation is valid.
	Valid() bool
}

Validator can be implemented by types that can validate their data. The Valid method should return true if the data is valid, false otherwise.

Because Valid can't tell why the data is invalid, Validate, TryValidate, DeepValidate and ValidatorAsValidatable return an error naming the type and the value formatted with %#v, like `invalid main.Status value: "unknown"`. So the whole value is part of the error message. Implement Validatable instead for other errors, like for a value that must not be logged, such as a password, or that can be large, because the error of Validatable.Validate is returned unchanged.

func CombinedValidator

func CombinedValidator(validators ...Validator) Validator

CombinedValidator creates a Validator whose Valid method returns false if any of the passed validators Valid methods returned false, else it returns true. This is equivalent to creating a Validators slice.

type ValidatorAsValidatable

type ValidatorAsValidatable struct {
	Validator
}

ValidatorAsValidatable wraps a Validator as a Validatable, returning an error naming the type and value of the Validator when Validator.Valid() returns false. This allows you to use a simple boolean validator in contexts that require detailed error information.

func (ValidatorAsValidatable) Validate

func (v ValidatorAsValidatable) Validate() error

Validate returns an error if the wrapped validator is not valid. A Validator that Validate does not validate returns nil: nil, a nil func, a nil pointer to a type implementing Validator with a value receiver, and a value whose Valid method is promoted from a nil embedded pointer or interface.

type ValidatorFunc

type ValidatorFunc func() bool

ValidatorFunc implements the Validator interface with a function. This allows you to use a function as a validator.

func (ValidatorFunc) Valid

func (f ValidatorFunc) Valid() bool

Valid returns if the data of the implementation is valid.

type Validators

type Validators []Validator

Validators is a slice of Validator implementations. It implements the Validator interface itself, returning true only if all validators are valid.

func (Validators) Valid

func (v Validators) Valid() bool

Valid returns if the data of the implementation is valid. Returns false if any validator in the slice returns false. Elements that Validate does not validate are skipped: nil, a nil func, a nil pointer to a type implementing Validator with a value receiver, and a value whose Valid method is promoted from a nil embedded pointer or interface.

Directories

Path Synopsis
Package account provides account number types with validation, numeric conversion, and SQL, JSON, XML, and text integration.
Package account provides account number types with validation, numeric conversion, and SQL, JSON, XML, and text integration.
Package bank provides banking identifier types for Go applications.
Package bank provides banking identifier types for Go applications.
Package charset converts text between UTF-8 and other character encodings and handles Unicode Byte Order Marks (BOM).
Package charset converts text between UTF-8 and other character encodings and handles Unicode Byte Order Marks (BOM).
findencoding
Package findencoding is a debugging aid for finding the character encoding of a text file by eye.
Package findencoding is a debugging aid for finding the character encoding of a text file by eye.
Package country provides ISO 3166-1 alpha-2 country codes.
Package country provides ISO 3166-1 alpha-2 country codes.
Package date provides calendar dates as ISO 8601 strings (YYYY-MM-DD) with lenient parsing of the many ways people write dates.
Package date provides calendar dates as ISO 8601 strings (YYYY-MM-DD) with lenient parsing of the many ways people write dates.
Package email provides lenient email address parsing and normalization, address lists and sets, and the parsing and building of email messages.
Package email provides lenient email address parsing and normalization, address lists and sets, and the parsing and building of email messages.
Package float parses and formats floating point numbers with locale-dependent separators and rounds them to decimal places.
Package float parses and formats floating point numbers with locale-dependent separators and rounds them to decimal places.
collections
Package collections reproduces the abstract collection interfaces documented by the Go 1.28 collections proposal, https://go.dev/issue/80590.
Package collections reproduces the abstract collection interfaces documented by the Go 1.28 collections proposal, https://go.dev/issue/80590.
collections/settest
Package settest provides a reusable conformance test for the abstract set interface of the Go 1.28 collections proposal, https://go.dev/issue/80590.
Package settest provides a reusable conformance test for the abstract set interface of the Go 1.28 collections proposal, https://go.dev/issue/80590.
normtest
Package normtest provides a reusable conformance test for the reading and writing contract of the string types of this module, like country.Code, vat.ID or date.Date.
Package normtest provides a reusable conformance test for the reading and writing contract of the string types of this module, like country.Code, vat.ID or date.Date.
pq
pq/oid
Package oid contains OID constants as defined by the Postgres server.
Package oid contains OID constants as defined by the Postgres server.
xmlattrtest
Package xmlattrtest checks how encoding/xml writes a type as attribute.
Package xmlattrtest checks how encoding/xml writes a type as attribute.
js module
Package language provides ISO 639-1 two-letter language codes.
Package language provides ISO 639-1 two-letter language codes.
gen-lang-maps command
Command gen-lang-maps regenerates the language package's ISO 639-3 lookup tables from the SIL reference data:
Command gen-lang-maps regenerates the language package's ISO 639-3 lookup tables from the SIL reference data:
Package mapset defines operations on sets represented either as map[K]struct{}, or as map[K]bool where the boolean value is ignored.
Package mapset defines operations on sets represented either as map[K]struct{}, or as map[K]bool where the boolean value is ignored.
Package money provides money amounts, ISO 4217 currencies, and rates with locale-aware parsing and SQL, JSON, and strfmt support.
Package money provides money amounts, ISO 4217 currencies, and rates with locale-aware parsing and SQL, JSON, and strfmt support.
Package notnull provides never-null counterparts of some types of package github.com/domonda/go-types/nullable, for NOT NULL columns and JSON fields that must not be null.
Package notnull provides never-null counterparts of some types of package github.com/domonda/go-types/nullable, for NOT NULL columns and JSON fields that must not be null.
Package nullable provides nullable wrapper types for database/sql and encoding/json, and the interfaces that describe nullable values across this module.
Package nullable provides nullable wrapper types for database/sql and encoding/json, and the interfaces that describe nullable values across this module.
Package queue provides an unbounded, goroutine-safe FIFO queue that delivers its items through a Go channel.
Package queue provides an unbounded, goroutine-safe FIFO queue that delivers its items through a Go channel.
Package set provides generic helper functions for sets represented as plain map[T]struct{} values with T constrained to cmp.Ordered.
Package set provides generic helper functions for sets represented as plain map[T]struct{} values with T constrained to cmp.Ordered.
Package strfmt converts between strings and typed Go values via reflection, for example to read the cells of a CSV file or a spreadsheet into struct fields and to write typed values into a localized export.
Package strfmt converts between strings and typed Go values via reflection, for example to read the cells of a CSV file or a spreadsheet into struct fields and to write typed values into a localized export.
Package strutil provides string helpers used across the go-types module.
Package strutil provides string helpers used across the go-types module.
stringfrom
Package stringfrom provides utilities for converting various Go types to strings with safe handling of nil pointers and customizable default values.
Package stringfrom provides utilities for converting various Go types to strings with safe handling of nil pointers and customizable default values.
Package uu provides UUID types with database/sql, encoding/json and text support.
Package uu provides UUID types with database/sql, encoding/json and text support.
Package vat validates and normalizes European VAT identification numbers.
Package vat validates and normalizes European VAT identification numbers.

Jump to

Keyboard shortcuts

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