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:
- Set: generic set type backed by map[T]struct{} with set algebra and JSON marshaling. See also SetToSortedSlice, SetToRandomizedSlice, ReduceSet, ReduceSlice, SliceContainsAll, SliceContainsAny.
- Validator / Validatable: interfaces for boolean and error-based validation, with Validators / Validatables composition helpers, CombinedValidator / CombinedValidatable, and Validate, TryValidate, and DeepValidate entry points for recursive reflection-based validation.
- Normalizable / NormalizableValidator: interfaces for one canonical form via Normalized. SQL, JSON and XML reading and writing do not call it, except date.Date on SQL.
- FromPtr, FromPtrOr: generic pointer helpers.
- Yield, Yield2, YieldErr, Seq2NilError: adapters for the iter package introduced in Go 1.23.
- LenString: string with min/max length constraints.
- Finder: interface for finding sub-strings in text, implemented by bank.IBANFinder, bank.BICFinder, *date.Finder, vat.IDFinder, and money.AmountFinder.
- KeyMutex: generic per-key mutex pool whose zero value is usable.
- CanMarshalJSON: static check whether encoding/json can encode a type. It does not inspect field, element, or map value types, so it can report true for a type that fails to marshal.
- CompareReflectValue: three-way comparison of two reflect.Value arguments, used to sort map keys in DeepValidate.
Subpackages ¶
Domain value types with validation, normalization, and SQL/JSON integration:
- github.com/domonda/go-types/account: account numbers
- github.com/domonda/go-types/bank: IBAN, BIC, CAMT.053
- github.com/domonda/go-types/country: ISO 3166-1 country codes
- github.com/domonda/go-types/date: ISO 8601 dates, year-month, year-quarter
- github.com/domonda/go-types/email: addresses, lists, MIME parsing
- github.com/domonda/go-types/language: ISO 639-1 language codes
- github.com/domonda/go-types/money: amounts, currencies, rates
- github.com/domonda/go-types/uu: UUID type with nullable and slice variants
- github.com/domonda/go-types/vat: European VAT identification numbers
Wrappers for SQL/JSON null semantics:
- github.com/domonda/go-types/nullable: empty/zero round-trips as NULL
- github.com/domonda/go-types/notnull: nil/empty round-trips as '{}' / []
String and numeric utilities:
- github.com/domonda/go-types/charset: encoding, BOM, UTF-16/32
- github.com/domonda/go-types/float: locale-aware parsing and formatting
- github.com/domonda/go-types/strfmt: reflection-driven scan/format
- github.com/domonda/go-types/strutil: string manipulation and sets
- github.com/domonda/go-types/strutil/stringfrom: pointers and values to strings with a default for nil
Generic collection helpers:
- github.com/domonda/go-types/mapset: set functions over map[K]struct{} and map[K]bool, mirroring the proposed container/mapset
- github.com/domonda/go-types/queue: concurrent FIFO queue
- github.com/domonda/go-types/set: set helpers over map[T]struct{}
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 ¶
- func CanMarshalJSON(t reflect.Type) bool
- func CompareReflectValue(a, b reflect.Value) int
- func DeepValidate(v any) []error
- func FromPtr[T any](ptr *T) T
- func FromPtrOr[T any](ptr *T, defaultValue T) T
- func ReduceSet[S ~map[T]struct{}, T cmp.Ordered, R any](set S, reduceFunc func(last R, val T) R) (result R)
- func ReduceSlice[S ~[]T, T cmp.Ordered, R any](slice S, reduceFunc func(last R, val T) R) (result R)
- func Seq2NilError[K any](seq iter.Seq[K]) iter.Seq2[K, error]
- func SetToRandomizedSlice[S ~map[T]struct{}, T cmp.Ordered](set S) []T
- func SetToSortedSlice[S ~map[T]struct{}, T cmp.Ordered](set S) []T
- func SliceContainsAll[T comparable](outer []T, inner ...T) bool
- func SliceContainsAny[T comparable](outer []T, inner ...T) bool
- func TryValidate(v any) (implemented bool, err error)
- func ValidOr[T Validator](val, def T) T
- func Validate(v any) error
- func ValidatedOr[T Validatable](val, def T) T
- func Yield[V any](value V) iter.Seq[V]
- func Yield2[K, V any](key K, value V) iter.Seq2[K, V]
- func YieldErr[K any](err error) iter.Seq2[K, error]
- type Finder
- type KeyMutex
- type LenString
- func (s *LenString) MarshalJSON() (text []byte, err error)
- func (s *LenString) MarshalText() (text []byte, err error)
- func (s *LenString) MaxLen() int
- func (s *LenString) MinLen() int
- func (s *LenString) ScanString(source string, validate bool) error
- func (s *LenString) SetString(str string) error
- func (s *LenString) String() string
- func (s *LenString) UnmarshalJSON(text []byte) error
- func (s *LenString) UnmarshalText(text []byte) error
- func (s *LenString) Validate() error
- type Normalizable
- type NormalizableValidator
- type Set
- func (set Set[T]) All() iter.Seq[T]
- func (set Set[T]) Clear()
- func (set Set[T]) Clone() Set[T]
- func (set Set[T]) Contains(val T) bool
- func (set Set[T]) ContainsAll(seq iter.Seq[T]) bool
- func (set Set[T]) ContainsAny(vals ...T) bool
- func (set Set[T]) ContainsSet(other Set[T]) bool
- func (set Set[T]) Delete(val T) bool
- func (set Set[T]) DeleteAll(seq iter.Seq[T]) bool
- func (set Set[T]) DeleteFunc(del func(T) bool) bool
- func (set Set[T]) Difference(other Set[T]) Set[T]
- func (set Set[T]) DifferenceWith(other Set[T])
- func (set Set[T]) Equal(other Set[T]) bool
- func (set Set[T]) GetOne() T
- func (set Set[T]) Insert(val T) bool
- func (set Set[T]) InsertAll(seq iter.Seq[T]) bool
- func (set Set[T]) Intersection(other Set[T]) Set[T]
- func (set Set[T]) IntersectionWith(other Set[T])
- func (set Set[T]) Intersects(other Set[T]) bool
- func (set Set[T]) IsEmpty() bool
- func (set Set[T]) IsNull() bool
- func (set Set[T]) Len() int
- func (set Set[T]) Map(mapFunc func(T) (T, bool)) Set[T]
- func (set Set[T]) MarshalJSON() ([]byte, error)
- func (set Set[T]) Sorted() []T
- func (set Set[T]) String() string
- func (set Set[T]) SymmetricDifference(other Set[T]) Set[T]
- func (set Set[T]) SymmetricDifferenceWith(other Set[T])
- func (set Set[T]) Union(other Set[T]) Set[T]
- func (set Set[T]) UnionWith(other Set[T])
- func (set *Set[T]) UnmarshalJSON(j []byte) error
- type StaticValidatable
- type StaticValidator
- type Validatable
- type ValidatableFunc
- type Validatables
- type Validator
- type ValidatorAsValidatable
- type ValidatorFunc
- type Validators
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CanMarshalJSON ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Yield returns an iterator that yields a single value. This is useful for converting a single value into an iterator sequence.
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 (*KeyMutex[T]) IsLocked ¶
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.
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 ¶
MustLenString returns a LenString or panics on errors from Validate. Use this when you're certain the string meets the length constraints.
func NewLenString ¶
NewLenString returns a new LenString without validating it. Use this when you want to create a LenString and validate it separately.
func (*LenString) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface.
func (*LenString) MarshalText ¶
MarshalText implements the encoding.TextMarshaler interface.
func (*LenString) ScanString ¶
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 ¶
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 ¶
String returns the string or "<nil>". String implements the fmt.Stringer interface.
func (*LenString) UnmarshalJSON ¶
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 ¶
UnmarshalText implements the encoding.TextUnmarshaler interface. It validates the text length before setting the string value.
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 ¶
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 ¶
NewSet creates a new Set containing the provided values. Duplicate values are automatically deduplicated.
func (Set[T]) All ¶
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]) Contains ¶
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 ¶
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 ¶
ContainsAny returns true if the set contains any of the specified values.
func (Set[T]) ContainsSet ¶
ContainsSet returns true if this set contains all values from the other set.
func (Set[T]) Delete ¶
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 ¶
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 ¶
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 ¶
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 ¶
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]) 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 ¶
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 ¶
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 ¶
Intersection returns a new set containing only values that exist in both sets.
func (Set[T]) IntersectionWith ¶
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 ¶
Intersects reports whether this set and the other set have at least one value in common.
func (Set[T]) IsNull ¶
IsNull implements the nullable.Nullable interface by returning true if the set is nil.
func (Set[T]) Map ¶
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 ¶
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 ¶
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 ¶
SymmetricDifference returns a new set containing the values that exist in either set but not in both.
func (Set[T]) SymmetricDifferenceWith ¶
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 ¶
Union returns a new set containing all values from both this set and the other set.
func (Set[T]) UnionWith ¶
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 ¶
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 ¶
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.
Source Files
¶
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/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. |