types

package module
v0.0.0-...-81febb3 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2026 License: MIT Imports: 12 Imported by: 3

README

go-types

Go Reference Go Report Card Go Go version license

A comprehensive Go library providing enhanced type definitions, validation, and utility functions for common data types and operations.

Overview

go-types is a collection of Go packages that extend the standard library with additional type definitions, validation frameworks, and utility functions. It provides type-safe implementations for common data structures and operations, making it easier to work with validated data, nullable types, and specialized data formats.

Features

  • Type-Safe Collections: Generic Set implementation with comprehensive operations
  • Validation Framework: Flexible validation system with both boolean and error-based validation
  • Nullable Types: Support for nullable values with proper JSON marshaling/unmarshaling
  • Specialized Data Types: Email addresses, dates, money amounts, VAT IDs, and more
  • String Utilities: Enhanced string manipulation and formatting functions
  • Iterator Utilities: Helper functions for Go's iterator patterns
  • JSON Support: Comprehensive JSON marshaling/unmarshaling for all types

Packages

Package Description
types (root) Generic Set, validation framework, pointer/iterator/JSON helpers, LenString, Finder, KeyMutex
account Alphanumeric account numbers with validation and SQL/JSON/XML support
bank IBAN, BIC/SWIFT, bank accounts, and ISO 20022 CAMT.053 statement parsing
charset UTF-8/16/32 encoding, BOM detection, and golang.org/x/text integration
country ISO 3166-1 alpha-2 country codes with normalization and EU membership
date ISO 8601 Date, YearMonth, YearQuarter, lenient locale-aware parsing
email Lenient email parsing, address lists/sets, MIME and TNEF message handling
float Locale-aware float parsing/formatting and a JSON-tolerant float type
language ISO 639-1 language codes with normalization
money Monetary amounts, ISO 4217 currencies, currency+amount pairs, and rates
notnull Never-null SQL/JSON wrappers (nil slices serialize as '{}' / [])
nullable SQL-friendly nullable wrappers and the generic Type[T]
queue Generic unbounded concurrent FIFO queue exposed as a channel
set Generic set helpers over the idiomatic map[T]struct{} representation
strfmt Reflection-driven string scan/format with locale presets
strutil String manipulation, trimming, transliteration, domain extraction, sets
uu UUID type with ID, NullableID, IDSlice, IDSet, and helpers
vat European VAT IDs with per-country format and checksum validation

Core Packages

Main Package (types)

The main package provides core utilities and type definitions:

Collections
  • Set[T]: A generic set implementation with comprehensive operations (union, intersection, difference, etc.)
  • Slice Utilities: Functions for checking slice containment (SliceContainsAll, SliceContainsAny)
Validation Framework
  • Validator: Interface for boolean validation
  • ValidatErr: Interface for validation with detailed error information
  • DeepValidate: Recursive validation of nested structures
  • CombinedValidator: Combine multiple validators
  • CompareReflectValue: Comparator for slices.SortFunc that orders reflect.Values across all orderable kinds (numerics, strings, bool, complex, pointers, channels, arrays, slices including []byte, structs, and interfaces) and returns 0 for non-orderable or mismatched-type values
Utility Functions
  • Pointer Utilities: Safe pointer dereferencing (Ptr, FromPtr, FromPtrOr)
  • Iterator Helpers: Functions for working with Go's iterator patterns (Yield, Yield2, YieldErr)
  • JSON Utilities: Check if types can be marshaled as JSON (CanMarshalJSON)
Specialized Types
  • LenString: String with length constraints and validation
  • Finder: Interface for pattern matching in byte slices
Subpackages
email - Email Address Handling
  • Address: Email address type with normalization and validation
  • AddressList: Collection of email addresses
  • AddressSet: Set of unique email addresses
  • Attachment: Email attachment handling
  • Message: Complete email message structure
  • ParseAddress: Flexible email address parsing
money - Financial Data Types
  • Amount: Money amount with decimal precision handling
  • Currency: Currency codes and information
  • CurrencyAmount: Combined currency and amount
  • Rate: Exchange rate handling
  • AmountParser: Parse monetary values from strings
  • CurrencyParser: Parse currency information
date - Date Handling
  • Date: Date type with comprehensive parsing and formatting
  • NullableDate: Nullable date type
  • DateNames: Localized date names
  • DateFinder: Find dates in text
  • DateFormatter: Format dates in various styles
  • DateParser: Parse dates from strings
bank - Banking Data Types
  • IBAN: International Bank Account Number handling
  • BIC: Bank Identifier Code handling
  • Account: Bank account information
  • CAMT53: ISO 20022 CAMT.053 message handling
  • IBANParser/BICParser: Parse banking identifiers
vat - VAT ID Handling
  • ID: VAT identification number with country-specific validation
  • IDFinder: Find VAT IDs in text
  • IDParser: Parse VAT IDs from strings
  • NullableID: Nullable VAT ID type
country - Country Information
  • Code: ISO country codes
  • NullableCode: Nullable country code
  • Country Data: Comprehensive country information
language - Language Codes
  • Code: ISO 639 language codes
  • Constants: Language code constants
  • ISO 639-3: Language-name and macrolanguage lookups
nullable - Nullable Types
  • Type[T]: Generic nullable type wrapper
  • Arrays: Nullable array types for various data types
  • NonEmptyString: String that cannot be empty
  • TrimmedString: String with automatic trimming
  • Time: Nullable time type
strutil - String Utilities
  • String Manipulation: Enhanced string functions
  • DomainName: Domain name validation and manipulation
  • HTML Utilities: HTML processing functions
  • Random: Random string generation
  • StringSet: Set of strings
  • StrMutex: String-based mutex for synchronization
strfmt - String Formatting
  • Format: String format detection and handling
  • Scanner: String scanning utilities
  • Formatter: String formatting functions
  • Detector: Format detection algorithms
float - Float Utilities
  • Parse: Enhanced float parsing with tolerance
  • Format: Float formatting utilities
  • Tolerant: Tolerant float operations
queue - Queue Implementation
  • Queue[T]: Generic, unbounded, goroutine-safe FIFO queue consumed via a channel
  • New[T]: Constructor configured by functional options (ChanLen, InitialBufferSize)
  • Non-blocking Add: An internal growable ring buffer absorbs bursts, so producers never block
charset - Character Set Handling
  • Encoding: Character encoding detection and conversion
  • UTF8/UTF16/UTF32: Unicode handling utilities
  • BOM: Byte Order Mark handling
uu - UUID Utilities
  • ID: UUID handling and generation
  • IDContext: Context-aware UUID operations
  • IDMutex: UUID-based mutex for synchronization
  • IDSet: Set of UUIDs
  • IDSlice: Slice of UUIDs with utilities

Installation

go get github.com/domonda/go-types

Usage Examples

Sets
package main

import (
    "fmt"
    "github.com/domonda/go-types"
)

func main() {
    // Create a set
    set1 := types.NewSet(1, 2, 3, 4, 5)
    set2 := types.NewSet(4, 5, 6, 7, 8)
    
    // Set operations
    union := set1.Union(set2)
    intersection := set1.Intersection(set2)
    difference := set1.Difference(set2)
    
    fmt.Printf("Union: %v\n", union.Sorted())
    fmt.Printf("Intersection: %v\n", intersection.Sorted())
    fmt.Printf("Difference: %v\n", difference.Sorted())
}
Validation
package main

import (
    "fmt"
    "github.com/domonda/go-types"
)

type User struct {
    Name  string
    Email string
    Age   int
}

func (u User) Validate() error {
    if u.Name == "" {
        return fmt.Errorf("name is required")
    }
    if u.Age < 0 {
        return fmt.Errorf("age must be non-negative")
    }
    return nil
}

func main() {
    user := User{Name: "John", Email: "john@example.com", Age: 25}
    
    // Validate single value
    if err := types.Validate(user); err != nil {
        fmt.Printf("Validation error: %v\n", err)
    }
    
    // Deep validation of nested structures
    if err := types.DeepValidate(user); err != nil {
        fmt.Printf("Deep validation error: %v\n", err)
    }
}
Email Addresses
package main

import (
    "fmt"
    "github.com/domonda/go-types/email"
)

func main() {
    // Parse and normalize email address
    addr, err := email.NormalizedAddress("John Doe <john@example.com>")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("Normalized: %s\n", addr)
    
    // Create address list
    list := email.AddressListJoin(addr, email.Address("jane@example.com"))
    fmt.Printf("Address list: %v\n", list)
}
Money Amounts
package main

import (
    "fmt"
    "github.com/domonda/go-types/money"
)

func main() {
    // Parse money amount
    amount, err := money.ParseAmount("123.45", 2) // 2 decimal places
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("Amount: %v\n", amount)
    
    // Create currency amount
    currencyAmount := money.CurrencyAmount{
        Amount:   amount,
        Currency: money.Currency("USD"),
    }
    
    fmt.Printf("Currency amount: %v\n", currencyAmount)
}
Dates
package main

import (
    "fmt"
    "github.com/domonda/go-types/date"
)

func main() {
    // Parse date from string
    d, err := date.Normalize("2024-01-15")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("Date: %s\n", d)
    fmt.Printf("Is valid: %v\n", d.Valid())
}
Nullable Types
package main

import (
    "fmt"
    "github.com/domonda/go-types/nullable"
)

func main() {
    // Create nullable string
    nullableStr := nullable.New("hello")
    
    fmt.Printf("Value: %v\n", nullableStr.Value())
    fmt.Printf("Is null: %v\n", nullableStr.IsNull())
    
    // Set to null
    nullableStr.SetNull()
    fmt.Printf("Is null after SetNull: %v\n", nullableStr.IsNull())
}

JSON Support

All types in go-types support JSON marshaling and unmarshaling:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/domonda/go-types"
)

func main() {
    // Set JSON marshaling
    set := types.NewSet(1, 2, 3, 4, 5)
    
    jsonData, err := json.Marshal(set)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("JSON: %s\n", string(jsonData))
    
    // Unmarshal back to set
    var newSet types.Set[int]
    err = json.Unmarshal(jsonData, &newSet)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("Unmarshaled set: %v\n", newSet.Sorted())
}

Testing

The library includes comprehensive tests for all functionality:

go test ./...

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Dependencies

  • Go 1.24.0 or later
  • Standard library packages
  • External dependencies are minimal and well-maintained

Performance

The library is designed with performance in mind:

  • Generic types provide compile-time type safety
  • Efficient data structures (sets implemented as maps)
  • Minimal allocations where possible
  • Comprehensive caching for expensive operations

Security

Security considerations:

  • Input validation for all user-provided data
  • Safe handling of nullable types
  • Proper error handling and reporting
  • No unsafe operations exposed in public API

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. SQL is supported via database/sql.Scanner and database/sql/driver.Valuer; JSON via encoding/json.Marshaler and encoding/json.Unmarshaler; most types additionally implement encoding.TextMarshaler / encoding.TextUnmarshaler and provide a JSONSchema method compatible with github.com/invopop/jsonschema.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidValue = errors.New("invalid value")

ErrInvalidValue means that a value is not valid, returned by Validate() and ValidatorAsValidatErr.Validate().

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 implementing encoding.TextMarshaler,
  • t is a pointer or interface to a marshalable element type.

Kinds rejected by encoding/json (complex, chan, func, unsafe.Pointer) return false. Because field/element types are not inspected recursively, a struct or array containing an unsupported field type may pass this check and still fail at runtime. Value-dependent failures such as float NaN/Inf are likewise invisible here.

func CompareReflectValue

func CompareReflectValue(a, b reflect.Value) int

CompareReflectValue compares two reflect.Values. Returns 0 if the values are not of the same type or not of an orderable kind, so the function is safe to use as the less function for slices.SortFunc on slices of mixed or non-orderable [reflect.Value]s (the order of such elements is left unchanged).

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 (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,
  • follows pointers and interfaces to any depth (nil values stop the descent),
  • recurses into exported struct fields, slice and array elements, and map values (map keys are not validated, but are sorted with CompareReflectValue so error order is deterministic),
  • skips unexported struct fields, which cannot be inspected via reflection.

Errors are prefixed with a human-readable path to the offending value, e.g. "struct field Users -> element [1] -> struct field Name: invalid value".

Cycles via self-referential pointers or maps are not detected and will recurse until the stack overflows; pass acyclic data.

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 Ptr

func Ptr[T any](value T) *T

Ptr returns a new pointer to a copy of the passed value. This is useful for creating pointers to values that need to be passed by reference.

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.

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.

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 random order.

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.

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 outer has fewer elements than inner or if any element in inner is not found in 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) (err error, isValidatable bool)

TryValidate returns an error and true if v implements ValidatErr or Validator and the methods ValidatErr.Validate() or Validator.Valid() indicate an invalid value. The error from ValidatErr.Validate() is returned directly, and ErrInvalidValue is returned if Validator.Valid() is false. If v does not implement ValidatErr or Validator then nil and false will be returned. The boolean return value indicates whether the value was validatable.

func Validate

func Validate(v any) error

Validate returns an error if v implements ValidatErr or Validator and the methods ValidatErr.Validate() or Validator.Valid() indicate an invalid value. The error from ValidatErr.Validate() is returned directly, and ErrInvalidValue is returned if Validator.Valid() is false. If v does not implement ValidatErr or Validator then nil will be returned.

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 index pairs [start, end] for each match.
	// 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.

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 wether a key is locked.

func (*KeyMutex[T]) Lock

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

Lock the mutex for a given key

func (*KeyMutex[T]) Unlock

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

Unlock the mutex for a given key.

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. LenString implements the encoding.UnmarshalText, json.Unmarshaler, and strfmt.StringAssignable 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.

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 ValidatErr 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, providing a comprehensive solution 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]) Add

func (set Set[T]) Add(val T)

Add adds a value to the set.

func (Set[T]) AddSet

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

AddSet adds all values from another set to this set.

func (Set[T]) AddSlice

func (set Set[T]) AddSlice(vals []T)

AddSlice adds all values from the slice to the set.

func (Set[T]) Clear

func (set Set[T]) Clear()

Clear removes all values from the set.

func (Set[T]) Clone

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

Clone creates a deep copy of the set.

func (Set[T]) Contains

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

Contains returns true if the set contains the specified value.

func (Set[T]) ContainsAll

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

ContainsAll returns true if the set contains all of the specified values.

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)

Delete removes a value from the set.

func (Set[T]) DeleteSet

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

DeleteSet removes all values from the other set from this set.

func (Set[T]) DeleteSlice

func (set Set[T]) DeleteSlice(vals []T)

DeleteSlice removes all values from the slice from the set.

func (Set[T]) Difference

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

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

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

func (Set[T]) MarshalJSON

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

MarshalJSON implements encoding/json.Marshaler by returning the JSON null value for an empty (null) string.

func (Set[T]) Sorted

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

Sorted returns a slice containing all values in the set, sorted in ascending order.

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.

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

type StaticValidatErr

type StaticValidatErr struct {
	Err error
}

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

func (StaticValidatErr) Validate

func (v StaticValidatErr) 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 ValidatErr

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

ValidatErr 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.

func CombinedValidatErr

func CombinedValidatErr(validatErrs ...ValidatErr) ValidatErr

CombinedValidatErr creates a ValidatErr whose Validate method returns the first error from the passed validatErrs Validate methods or nil if none returned an error. This is equivalent to creating a ValidatErrs slice.

type ValidatErrFunc

type ValidatErrFunc func() error

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

func (ValidatErrFunc) Validate

func (f ValidatErrFunc) Validate() error

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

type ValidatErrs

type ValidatErrs []ValidatErr

ValidatErrs is a slice of ValidatErr implementations. It implements the ValidatErr interface itself, returning the first error encountered.

func (ValidatErrs) Validate

func (v ValidatErrs) Validate() error

Validate returns an error if the data of the implementation is not valid. Returns the first error from any validator in the slice, or nil if all are valid.

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.

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 ValidatorAsValidatErr

type ValidatorAsValidatErr struct {
	Validator
}

ValidatorAsValidatErr wraps a Validator as a ValidatErr, returning ErrInvalidValue when Validator.Valid() returns false. This allows you to use a simple boolean validator in contexts that require detailed error information.

func (ValidatorAsValidatErr) Validate

func (v ValidatorAsValidatErr) Validate() error

Validate returns an error if the wrapped validator is not valid.

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.

Directories

Path Synopsis
Package account provides account number handling with validation, parsing, and database integration for Go applications.
Package account provides account number handling with validation, parsing, and database integration for Go applications.
Package bank provides comprehensive banking data types and utilities for Go applications.
Package bank provides comprehensive banking data types and utilities for Go applications.
findencoding
Package findencoding provides utilities for detecting and testing character encodings in text files, particularly useful for debugging encoding issues and finding the correct encoding for unknown text data.
Package findencoding provides utilities for detecting and testing character encodings in text files, particularly useful for debugging encoding issues and finding the correct encoding for unknown text data.
Package country provides comprehensive country code handling and validation based on ISO 3166-1 alpha-2 standards for Go applications.
Package country provides comprehensive country code handling and validation based on ISO 3166-1 alpha-2 standards for Go applications.
Package date provides comprehensive date handling and validation utilities for Go applications with support for multiple date formats and internationalization.
Package date provides comprehensive date handling and validation utilities for Go applications with support for multiple date formats and internationalization.
Package email provides comprehensive email address handling, parsing, validation, and message processing utilities for Go applications.
Package email provides comprehensive email address handling, parsing, validation, and message processing utilities for Go applications.
Package float provides utilities for working with floating-point numbers in Go.
Package float provides utilities for working with floating-point numbers in Go.
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.
js module
Package language provides comprehensive language code handling and validation based on ISO 639-1 standards for Go applications.
Package language provides comprehensive language code handling and validation based on ISO 639-1 standards for Go applications.
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 nullable provides interfaces and utilities for handling nullable values in Go.
Package nullable provides interfaces and utilities for handling nullable values in Go.
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.

Jump to

Keyboard shortcuts

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