### Install go-types Source: https://github.com/domonda/go-types/blob/master/_autodocs/README.md Install the go-types library using the go get command. ```bash go get github.com/domonda/go-types ``` -------------------------------- ### Account String Method Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/bank.md Demonstrates how to use the String() method to get a human-readable representation of an account. ```go acc := &bank.Account{ IBAN: "DE89370400440532013000", BIC: "DEUTDEDD", Currency: "EUR", } fmt.Println(acc.String()) ``` -------------------------------- ### Queue Configuration Examples Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/account-charset-float.md Provides examples of configuring a generic queue with different channel lengths and initial buffer sizes for varying throughput and latency requirements. ```go // High throughput, large buffers q := queue.New[string]( queue.ChanLen(256), queue.InitialBufferSize(512), ) // Low latency, small buffers q := queue.New[string]( queue.ChanLen(8), queue.InitialBufferSize(16), ) // Balanced q := queue.New[string]( queue.ChanLen(64), queue.InitialBufferSize(128), ) ``` -------------------------------- ### Quick Example: Parsing and Normalizing Data Source: https://github.com/domonda/go-types/blob/master/_autodocs/README.md Demonstrates parsing a monetary amount and a date, normalizing a currency, and creating a currency amount. This example requires the money and date packages. ```go package main import ( "fmt" "github.com/domonda/go-types/money" "github.com/domonda/go-types/date" ) func main() { // Parse and normalize amount, _ := money.ParseAmount("1.234,56", 2) d, _ := date.Normalize("25.12.2024") c, _ := money.NormalizeCurrency("eur") ca := money.NewCurrencyAmount(c, amount) fmt.Printf("Date: %s\nAmount: %v %s\n", d, amount, c) } ``` -------------------------------- ### Queue Configuration Examples Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/account-charset-float.md Provides example configurations for creating a queue with different throughput and latency characteristics using options for channel length and initial buffer size. ```APIDOC ### Example Configuration Patterns ```go // High throughput, large buffers q := queue.New[string]( queue.ChanLen(256), queue.InitialBufferSize(512), ) // Low latency, small buffers q := queue.New[string]( queue.ChanLen(8), queue.InitialBufferSize(16), ) // Balanced q := queue.New[string]( queue.ChanLen(64), queue.InitialBufferSize(128), ) ``` ``` -------------------------------- ### Example: Get Localized Language Names Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/country-language.md Demonstrates how to get the localized names of a language code in different target languages. ```go code := language.DE name, _ := code.Name(language.EN) // "German" name, _ := code.Name(language.DE) // "Deutsch" ``` -------------------------------- ### Install UUID package Source: https://github.com/domonda/go-types/blob/master/uu/README.md Use the go command to fetch the package dependency. ```bash go get github.com/domonda/go-types/uu ``` -------------------------------- ### Float Formatting Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/account-charset-float.md Shows how to format a float64 value into a localized string using `float.Format` and `FormatDetails`. This example uses German locale settings. ```go details := &float.FormatDetails{ Locale: "DE", DecimalPlaces: 2, } str := float.Format(1234.56, details) // str = "1.234,56" ``` -------------------------------- ### Example: Get Macrolanguage Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/country-language.md Shows how to find the macrolanguage code for a specific language code, like Simplified Chinese. ```go code := language.ZH // Simplified Chinese if macro, err := code.Macrolanguage(); err == nil { fmt.Println(macro) // "zh" (generic Chinese) } ``` -------------------------------- ### IDMutex Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/uu.md Demonstrates acquiring, working with, and releasing a mutex for a UUID using IDMutex. ```go m := uu.NewIDMutex() id := uu.IDv4() m.Lock(id) // Do work m.Unlock(id) ``` -------------------------------- ### Basic Producer-Consumer Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/queue.md Demonstrates a single producer goroutine adding items to the queue and a consumer loop processing them until the queue is closed. ```go func main() { q := queue.New[int]() defer q.Close() // Producer goroutine go func() { for i := 1; i <= 10; i++ { q.Add(i) } }() // Consumer loop for item := range q.Next() { fmt.Println(item) } } ``` -------------------------------- ### IDContext Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/uu.md Demonstrates storing and retrieving a UUID from a context using ContextWithID and IDFromContext. ```go ctx := context.Background() id := uu.IDv4() ctx = uu.ContextWithID(ctx, id) retrieved, ok := uu.IDFromContext(ctx) if ok { fmt.Println(retrieved) } ``` -------------------------------- ### Account Number Example Usage Source: https://github.com/domonda/go-types/blob/master/account/README.md Demonstrates creating an account number, checking if it's numeric, and converting a numeric account number to a uint64. ```go n, err := account.NumberFrom("AT-12345/67") if err != nil { log.Fatal(err) } fmt.Println(n.IsNumeric()) // false if u, err := account.Number("123456").Uint(); err == nil { fmt.Println(u) // 123456 } ``` -------------------------------- ### Example: Look Up Language Code Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/country-language.md Demonstrates using `LanguageFromName` to find the code for 'German'. ```go code, err := language.LanguageFromName("German", language.EN) // code = "de" ``` -------------------------------- ### ChanLen Option Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/queue.md Sets the capacity of the buffered channel exposed to consumers. A larger value allows more items to be ready for consumption. ```go q := queue.New[string](queue.ChanLen(100)) ``` -------------------------------- ### Type[T] Usage Examples Source: https://github.com/domonda/go-types/blob/master/nullable/README.md Demonstrates creating and interacting with the Type[T] generic nullable wrapper. ```go nullable.TypeFrom(42) // valid, value 42 nullable.TypeFromPtr[int](nil) // null nullable.TypeFromPtr(&someInt) // valid t.IsNull(); t.IsNotNull() t.Get(); t.GetOr(defaultVal); t.Ptr() t.Set(value); t.SetNull() ``` -------------------------------- ### SQL and JSON Integration Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/country-language.md Shows how country and language codes can be marshaled/unmarshaled for JSON and scanned/valued for SQL databases. ```go var c country.Code json.Unmarshal([]byte(`"DE"`), &c) // c = "DE" var l language.Code json.Unmarshal([]byte(`"en"`), &l) // l = "en" // Database var c country.Code row.Scan(&c) db.Exec("INSERT INTO users (country) VALUES (?)", c) ``` -------------------------------- ### Generic Nullable Wrapper Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/README.md Demonstrates the use of a generic nullable wrapper type. ```go type NullableAmount = nullable.Type[Amount] ``` -------------------------------- ### InitialBufferSize Option Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/queue.md Sets the initial capacity of the internal ring-buffer. A larger initial size can reduce reallocations during burst activity. ```go q := queue.New[string](queue.InitialBufferSize(256)) ``` -------------------------------- ### Date Finder Example Source: https://github.com/domonda/go-types/blob/master/date/README.md Demonstrates using the date.Finder to locate all date-like substrings within a given text. It utilizes language hints for locale-aware parsing. ```go f := date.NewFinder(language.DE) for _, idx := range f.FindAllIndex(text, -1) { fmt.Println(string(text[idx[0]:idx[1]])) } ``` -------------------------------- ### Multiple Producers Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/queue.md Shows how multiple producer goroutines can safely add items to the same queue. A WaitGroup ensures all producers finish before closing the queue. ```go func main() { q := queue.New[string]() defer q.Close() var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go func(id int) { defer wg.Done() for j := 0; j < 3; j++ { q.Add(fmt.Sprintf("producer-%d-item-%d", id, j)) } }(i) } go func() { wg.Wait() q.Close() }() for item := range q.Next() { fmt.Println(item) } } ``` -------------------------------- ### Normalize and Get Language Name Source: https://github.com/domonda/go-types/blob/master/language/README.md Normalize a language code to its canonical form and retrieve its English name. This example demonstrates using a constant directly. ```go code, err := language.Code("EN").Normalized() if err != nil { log.Fatal(err) } fmt.Println(code) // "en" fmt.Println(code.LanguageName()) // "English" // Using a constant directly: fmt.Println(language.DE.LanguageName()) // "German" ``` -------------------------------- ### JSON Serialization Source: https://github.com/domonda/go-types/blob/master/_autodocs/README.md Example of marshaling a go-types CurrencyAmount struct into JSON data. ```go data, _ := json.Marshal(ca) ``` -------------------------------- ### Example of using Scanner to parse a date string Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/account-charset-float.md Demonstrates how to use the Scanner to parse a date string into a specific date type. Requires a configured scanner and a destination variable. ```go scanner := strfmt.NewScanner(locale) var d date.Date _ = scanner.ScanString("2024-12-25", &d) ``` -------------------------------- ### SQL and JSON Marshaling/Unmarshaling Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/uu.md Shows how UUID types can be marshaled/unmarshaled for JSON and used with SQL database operations. ```go var id uu.ID err := json.Unmarshal([]byte(`"f47ac10b-58cc-4372-a567-0e02b2c3d479"`), &id) if err != nil { log.Fatal(err) } data, _ := json.Marshal(id) // data = `"f47ac10b-58cc-4372-a567-0e02b2c3d479"` // Database var id uu.ID row.Scan(&id) db.Exec("INSERT INTO users (id) VALUES (?)", id) ``` -------------------------------- ### Lenient Parsing and Normalization Source: https://github.com/domonda/go-types/blob/master/_autodocs/README.md Shows examples of lenient parsing and normalization for IBAN, dates, and monetary amounts, handling different formats and locales. ```go // Lenient parsing with normalization iban, err := bank.NormalizeIBAN("DE 89 3704 0044 0532 0130 00") date, err := date.Normalize("25.12.2024", language.DE) amount, err := money.ParseAmount("1.234,56", 2) ``` -------------------------------- ### Basic Queue Usage Example Source: https://github.com/domonda/go-types/blob/master/queue/README.md Illustrates the fundamental usage of the queue: creating a new queue, adding items, and consuming them concurrently using a goroutine and a `range` loop. Ensures the queue is closed upon function exit. ```go package main import ( "fmt" "github.com/domonda/go-types/queue" ) func main() { q := queue.New[string]() // DefaultChanLen, DefaultInitialBufferSize defer q.Close() go func() { for item := range q.Next() { fmt.Println("got:", item) } }() q.Add("a", "b", "c") q.Add("d", "e", "f") } ``` -------------------------------- ### Example: Splitting BOM and Decoding UTF-16LE Source: https://github.com/domonda/go-types/blob/master/charset/README.md Demonstrates how to split a Byte Order Mark (BOM) from byte data and then decode the remaining UTF-16LE encoded content into UTF-8. This is useful for processing files with unknown or mixed encodings. ```go data := []byte{0xFF, 0xFE, 'h', 0, 'i', 0} // UTF-16LE with BOM bom, rest := charset.SplitBOM(data) fmt.Println(bom) // "UTF-16LE" utf8Bytes, err := bom.Decode(rest) if err != nil { log.Fatal(err) } fmt.Println(string(utf8Bytes)) // "hi" ``` -------------------------------- ### JSON Deserialization Source: https://github.com/domonda/go-types/blob/master/_autodocs/README.md Example of unmarshaling JSON data into a go-types CurrencyAmount struct. ```go var ca money.CurrencyAmount json.Unmarshal([]byte(`{"Currency":"EUR","Amount":123.45}`), &ca) ``` -------------------------------- ### Get String Representation of Code Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/country-language.md Returns the code as a lowercase string. Useful for consistent string formatting. ```go func (c Code) String() string ``` -------------------------------- ### Float Parsing Examples Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/account-charset-float.md Demonstrates parsing float strings with different locale formats using the `float.Parse` function. Shows how to handle German and US number formats. ```go f, _ := float.Parse("1.234,56") // German format → 1234.56 f, _ := float.Parse("1,234.56") // US format → 1234.56 ``` -------------------------------- ### Generate Random Strings Source: https://github.com/domonda/go-types/blob/master/strutil/README.md Provides examples for generating random URL-safe base64 strings of a specified length, either as a string or a byte slice. ```go strutil.RandomString(32) // URL-safe base64 string of len 32 strutil.RandomStringBytes(32) // same, returned as []byte to save a copy ``` -------------------------------- ### Configuring Queue with Options Source: https://github.com/domonda/go-types/blob/master/queue/README.md Demonstrates how to create a new queue instance with custom configurations for consumer channel capacity and initial buffer size. ```go q := queue.New(queue.ChanLen(64), queue.InitialBufferSize(16)) ``` -------------------------------- ### Float ParseDetails Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/account-charset-float.md Illustrates the usage of `float.ParseDetails` to extract detailed parsing information, including the detected locale and number of decimal places from a given string. ```go val, orig, locale, decimals, _ := float.ParseDetails("1.234,56") // val = 1234.56, orig = "1.234,56", locale = "DE", decimals = 2 ``` -------------------------------- ### Account JSON Marshaling/Unmarshaling Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/bank.md Provides methods for JSON marshaling and unmarshaling, using struct field names as keys. Example shows unmarshaling JSON data into an Account struct. ```go func (a Account) MarshalJSON() ([]byte, error) func (a *Account) UnmarshalJSON(data []byte) error ``` ```go data := []byte(`{ "IBAN": "DE89370400440532013000", "BIC": "DEUTDEDD", "Currency": "EUR", "Holder": "John Doe" }`) var acc bank.Account json.Unmarshal(data, &acc) ``` -------------------------------- ### Parsing CAMT.053 Files Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/bank.md Example of parsing a CAMT.053 XML bank statement using Go's encoding/xml package. It decodes the XML into a CAMT53 struct and prints statement details and entries. ```go import ( "encoding/xml" "github.com/domonda/go-types/bank" ) var stmt bank.CAMT53 err := xml.NewDecoder(reader).Decode(&stmt) if err != nil { log.Fatal(err) } fmt.Printf("Statement ID: %s\n", stmt.StatementID) fmt.Printf("Period: %s to %s\n", stmt.FromDate, stmt.ToDate) for _, entry := range stmt.Entries { fmt.Printf("%s: %s %v\n", entry.BookingDate, entry.DebtorName, entry.Amount) } ``` -------------------------------- ### Write Go Types to Database Source: https://github.com/domonda/go-types/blob/master/_autodocs/configuration.md Shows how to insert `money.Amount`, `date.Date`, and `money.Currency` into a database, including proper NULL handling. ```go // Insert with proper NULL handling amount := money.Amount(100.50) d := date.Must("2024-12-25") c := money.Currency("EUR") err := db.QueryRow( "INSERT INTO transactions (amount, date, currency) VALUES (?, ?, ?) RETURNING id", amount, d, c, ).Scan(&id) ``` -------------------------------- ### Get Value and Status from Generic Nullable Type Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/nullable.md Demonstrates how to retrieve the wrapped value and its null status from a generic nullable type. The Get() method returns the value and a boolean indicating if it's non-null. ```go n := nullable.Of(42) val, ok := n.Get() if ok { fmt.Println(val) // 42 } nullVal := nullable.New[int]() _, ok = nullVal.Get() // ok == false ``` -------------------------------- ### Lenient Email Address Normalization Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/email.md Shows examples of lenient email address normalization, handling extra whitespace, missing brackets, and mixed case domains. Use for cleaning and standardizing email addresses. ```go email.NormalizedAddress(" John ") email.NormalizedAddress("john@EXAMPLE.COM") email.NormalizedAddress("John Doe john@example.com") // Repairs missing brackets ``` -------------------------------- ### Create and Manipulate a Set Source: https://github.com/domonda/go-types/blob/master/set/README.md Demonstrates creating a set with initial values, adding new values, and checking for containment using generic set helper functions. ```go package main import ( "fmt" "github.com/domonda/go-types/set" ) func main() { tags := set.New("go", "types", "validation") tags = set.Add(tags, "json") fmt.Println(set.Contains(tags, "go")) // true fmt.Println(set.ContainsAll(tags, "go", "json")) // true fmt.Println(set.ContainsAny(tags, "rust")) // false } ``` -------------------------------- ### Get Current YearQuarter Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/date.md Returns the current YearQuarter based on the local timezone. ```go func YearQuarterOfToday() YearQuarter ``` -------------------------------- ### Get Current YearMonth Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/date.md Returns the current YearMonth based on the local timezone. ```go func YearMonthOfToday() YearMonth ``` -------------------------------- ### Country Code Constructors and Conversion Source: https://github.com/domonda/go-types/blob/master/country/README.md Demonstrates creating and converting country codes. ```go country.Code("at") country.Code("DE").Nullable() ``` -------------------------------- ### Get UUID Version Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/uu.md Returns the UUID version number, which can range from 1 to 5. ```go func (id ID) Version() int ``` -------------------------------- ### Time Wrapper Construction and Parsing Source: https://github.com/domonda/go-types/blob/master/nullable/README.md Shows how to construct and parse Time values, including handling null and specific string formats. ```go TimeNow TimeFrom TimeFromPtr TimeParse(layout, value) TimeParseInLocation ``` -------------------------------- ### Get Number of UUIDs in Set Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/uu.md Returns the total number of unique UUIDs stored in the IDSet. ```go func (s IDSet) Len() int ``` -------------------------------- ### Get Wrapped UUID from NullableID Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/uu.md Returns the wrapped UUID from a NullableID. Returns nil if the NullableID is null. ```go func (n NullableID) Value() ID ``` -------------------------------- ### Create and Manipulate StringSet Source: https://github.com/domonda/go-types/blob/master/strutil/README.md Demonstrates creating a string set from initial values, adding more strings from a slice, and retrieving the sorted string representation. ```go s := strutil.NewStringSet("a", "b", "c") s.AddSlice([]string{"d", "e"}) s.Sorted() // []string sorted asc s.String() // `["a", "b", "c", "d", "e"]` ``` -------------------------------- ### Get UUID Variant Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/uu.md Returns the UUID variant as a string. This indicates the adherence to specific UUID standards. ```go func (id ID) Variant() string ``` -------------------------------- ### Create and Manipulate Nullable Strings Source: https://github.com/domonda/go-types/blob/master/README.md Illustrates creating a nullable string, checking its null status, and setting it to null. ```go 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()) } ``` -------------------------------- ### IDFinder.FindAllIndex Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/vat.md Scans a byte slice to find all occurrences of VAT IDs, returning their start and end indices. ```APIDOC ## FindAllIndex ### Description Finds all VAT IDs within a given byte slice and returns their index ranges. ### Method Signature ```go func (f *IDFinder) FindAllIndex(str []byte, n int) [][]int ``` ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | str | `[]byte` | The text to scan | | n | `int` | Limit: -1 = all, 0 = none, >0 = at most n | ### Returns Slice of `[start, end]` index pairs for each VAT ID found. ### Example ```go finder := vat.NewIDFinder() text := []byte("Company VAT ID: DE123456789 in Germany") for _, idx := range finder.FindAllIndex(text, -1) { fmt.Println(string(text[idx[0]:idx[1]])) // Output: DE123456789 } ``` ``` -------------------------------- ### Create and Operate on Sets Source: https://github.com/domonda/go-types/blob/master/_autodocs/configuration.md Demonstrates creating sets using types.NewSet and performing common set operations like intersection, difference, and union. ```go import ( "github.com/domonda/go-types" ) // Create and operate on sets allowed := types.NewSet(1, 2, 3, 4, 5) requested := types.NewSet(3, 4, 5, 6, 7) // Set operations intersection := allowed.Intersection(requested) // {3, 4, 5} difference := allowed.Difference(requested) // {1, 2, 6, 7} union := allowed.Union(requested) // {1, 2, 3, 4, 5, 6, 7} ``` -------------------------------- ### GetOrDefault for Currency Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/money.md Provides a safe way to get the currency value, returning a default if the currency is invalid or nil. ```go func (c *Currency) GetOrDefault(defaultVal Currency) Currency ``` -------------------------------- ### Nullable Variant Type Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/README.md Defines a nullable variant type. An empty value for this type is considered NULL. ```go type NullableCurrency string // NullableCurrency("").Valid() == true // Empty is NULL ``` -------------------------------- ### Non-Nullable Base Type Example Source: https://github.com/domonda/go-types/blob/master/_autodocs/README.md Defines a non-nullable base type. An empty value for this type is considered invalid. ```go type Currency string // Currency("").Valid() == false // Empty is invalid ``` -------------------------------- ### Scanning and Valuing Nullable Types with SQL Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/nullable.md Demonstrates how to scan NULL values from a SQL row into a nullable type and how to insert nullable types into the database. Ensure the nullable type implements `database/sql.Scanner` and `database/sql/driver.Valuer`. ```Go import "database/sql" var n nullable.Type[string] err := row.Scan(&n) if n.IsNull() { fmt.Println("NULL from database") } else { fmt.Println(n.Value()) } // Insert db.Exec("INSERT INTO users (name) VALUES (?)", n) ``` -------------------------------- ### NullSetable Interface Definition Source: https://github.com/domonda/go-types/blob/master/nullable/README.md Defines the NullSetable interface, extending Nullable with methods to set and get values, including null. ```go type NullSetable[T any] interface { Nullable SetNull() Set(T) Get() T // panics if null GetOr(T) T } ``` -------------------------------- ### AmountFinder FindAllIndex Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/money.md Scans byte slices for locale-aware monetary amount patterns, returning the start and end indices of all matches. ```go func NewAmountFinder(localeID string) *AmountFinder func (f *AmountFinder) FindAllIndex(str []byte, n int) [][]int ``` -------------------------------- ### Import strutil Package Source: https://github.com/domonda/go-types/blob/master/strutil/README.md Import the strutil package to use its string manipulation utilities. ```go import "github.com/domonda/go-types/strutil" ``` -------------------------------- ### Get Localized Name of Language Code Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/country-language.md Retrieves the localized name for a given language code. Specify the desired output language. ```go func (c Code) Name(lang Code) (string, error) ``` -------------------------------- ### Generate Version 4 UUID Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/uu.md Generates a version 4 random UUID. The example shows how to print the generated UUID string. ```go func IDv4() (id ID) ``` ```go id := uu.IDv4() fmt.Println(id.String()) // "f47ac10b-58cc-4372-a567-0e02b2c3d479" ``` -------------------------------- ### Parse and Normalize Email Addresses Source: https://github.com/domonda/go-types/blob/master/README.md Demonstrates parsing a display name and email address into a normalized format and creating an email address list. ```go package main import ( "fmt" "github.com/domonda/go-types/email" ) func main() { // Parse and normalize email address addr, err := email.NormalizedAddress("John Doe ") if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("Normalized: %s\n", addr) // Create address list list := email.AddressList{addr, email.Address("jane@example.com")} fmt.Printf("Address list: %v\n", list) } ``` -------------------------------- ### Import charset package Source: https://github.com/domonda/go-types/blob/master/charset/README.md Import the charset package to use its functionalities. ```go import "github.com/domonda/go-types/charset" ``` -------------------------------- ### Parse and Format Money Amounts Source: https://github.com/domonda/go-types/blob/master/README.md Shows how to parse a string into a money amount with a specified number of decimal places and create a currency amount object. ```go 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) } ``` -------------------------------- ### Run Go Tests Source: https://github.com/domonda/go-types/blob/master/README.md Command to execute all tests within the project's Go modules. ```bash go test ./... ``` -------------------------------- ### Unmarshal CAMT.053 XML Source: https://github.com/domonda/go-types/blob/master/bank/README.md Example of unmarshaling a CAMT.053 XML file into the CAMT53 struct using Go's encoding/xml package. ```go var stmt bank.CAMT53 err := xml.NewDecoder(reader).Decode(&stmt) ``` -------------------------------- ### Per-Key Locking with KeyMutex Source: https://github.com/domonda/go-types/blob/master/_autodocs/README.md Illustrates using KeyMutex for concurrent access control based on string keys. ```go // Per-key locking km := types.NewKeyMutex[string]() km.Lock("key1") defer km.Unlock("key1") ``` -------------------------------- ### Create Relative Dates Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/date.md Provides functions to get the current date, yesterday's date, or tomorrow's date in the local timezone. ```go func OfToday() Date func OfYesterday() Date func OfTomorrow() Date ``` -------------------------------- ### New Constructor Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/queue.md Creates a new unbounded FIFO queue. It can be configured using optional `Option`s for channel length and initial buffer size. ```APIDOC ## New Creates a new unbounded FIFO queue configured by optional `Option`s. ### Signature ```go func New[T any](options ...Option) Queue[T] ``` ### Behavior: - An internal goroutine pumps items from a ring-buffer into the consumer channel - The ring-buffer grows automatically as needed, ensuring `Add` never blocks - Without options, uses `DefaultChanLen` and `DefaultInitialBufferSize` ### Panics: - If `ChanLen < 0` - If `InitialBufferSize < 1` ### Example: ```go // Default configuration q := queue.New[string]() // Custom configuration q := queue.New[string]( queue.ChanLen(64), queue.InitialBufferSize(128), ) ``` ``` -------------------------------- ### Get Macrolanguage Code Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/country-language.md Identifies the macrolanguage code if the current code represents a dialect or specific variant. Useful for grouping related languages. ```go func (c Code) Macrolanguage() (Code, error) ``` -------------------------------- ### String Helper Functions Source: https://github.com/domonda/go-types/blob/master/strutil/README.md Provides utilities for string pointers, nil conversion, searching within slices, and generic joining and comparison. ```go strutil.Ptr(s), strutil.DerefPtr(p), strutil.EmptyStringToNil(s), strutil.StringToPtrEmptyToNil(s), strutil.IndexInStrings(s, slice), strutil.EqualPtrOrString(a, b), generic strutil.Join[T ~string](elems, sep), strutil.CompareStringsShorterFirst[T ~string](a, b), strutil.ConvertSlice[T, S ~string](s) ``` -------------------------------- ### Get VAT ID Country Code Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/vat.md Retrieves the 2-letter country code from a VAT ID. Assumes the ID is already in a valid format. ```go id := vat.ID("DE123456789") cc := id.CountryCode() // "DE" ``` -------------------------------- ### Database Write Operation Source: https://github.com/domonda/go-types/blob/master/_autodocs/README.md Demonstrates writing a go-types variable, like an IBAN, to a database using a prepared statement. ```go err := db.Exec("INSERT INTO accounts (iban) VALUES (?)", iban) ``` -------------------------------- ### Import Nullable Package Source: https://github.com/domonda/go-types/blob/master/nullable/README.md Import the nullable package to use its types and functions. ```go import "github.com/domonda/go-types/nullable" ``` -------------------------------- ### Scan Go Types from Database Source: https://github.com/domonda/go-types/blob/master/_autodocs/configuration.md Demonstrates scanning `money.Amount`, `date.Date`, and `money.Currency` types from a database row using `database/sql.Scanner`. ```go import ( "database/sql" "github.com/domonda/go-types/money" "github.com/domonda/go-types/date" ) var ( amount money.Amount d date.Date c money.Currency ) // Scan from database err := row.Scan(&amount, &d, &c) // Check for NULL if amount == 0 { // Handle NULL or zero amount } ``` -------------------------------- ### Configure Queue for Load Source: https://github.com/domonda/go-types/blob/master/_autodocs/configuration.md Configure queue behavior for different load scenarios, including minimal buffering for light loads and specific channel lengths and initial buffer sizes for heavy traffic. Supports per-key locking for resource coordination. ```go // Light load, minimal buffering q := queue.New[string]() // Heavy burst traffic q := queue.New[string]( queue.ChanLen(256), queue.InitialBufferSize(1024), ) // Per-key locking km := types.NewKeyMutex[string]() km.Lock("resource-id") defer km.Unlock("resource-id") ``` -------------------------------- ### Account String Method Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/bank.md Returns a human-readable string representation of the account. ```go func (a *Account) String() string ``` -------------------------------- ### Import VAT Package Source: https://github.com/domonda/go-types/blob/master/vat/README.md Import the necessary VAT package for using its functionalities. ```go import "github.com/domonda/go-types/vat" ``` -------------------------------- ### Account Normalize Method Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/bank.md Normalizes the account in place by normalizing IBAN, BIC, and currency. ```go func (a *Account) Normalize() ``` -------------------------------- ### Encoding Interface Source: https://github.com/domonda/go-types/blob/master/charset/README.md The Encoding interface defines methods for encoding and decoding byte slices to and from UTF-8, along with methods to get the encoding's name, string representation, and BOM. ```APIDOC ## Encoding Interface ```go type Encoding interface { Encode(utf8Str []byte) ([]byte, error) // UTF-8 → encoded Decode(encoded []byte) ([]byte, error) // encoded → UTF-8 Name() string String() string BOM() BOM } ``` Implementations of this interface are safe for concurrent use. ``` -------------------------------- ### Create New Set with Initial Values Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/main-types.md Constructs a new Set with the provided values. Duplicates are automatically handled. ```go func NewSet[T cmp.Ordered](vals ...T) Set[T] ``` ```go set := types.NewSet(1, 2, 3, 4, 5) fmt.Println(set.Sorted()) // Output: [1 2 3 4 5] ``` -------------------------------- ### Create New Queue with Default Configuration Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/queue.md Creates a new unbounded FIFO queue using default channel length and initial buffer size. ```go // Default configuration q := queue.New[string]() ``` -------------------------------- ### New Queue Constructor Source: https://github.com/domonda/go-types/blob/master/queue/README.md Creates a new instance of the Queue with optional configuration for channel length and initial buffer size. ```APIDOC ## New[T any](options ...Option) Queue[T] ### Description Creates a new concurrent-safe FIFO queue for items of type T. ### Parameters #### Options - `ChanLen(capacity int)`: Sets the capacity of the consumer channel. Defaults to 32. Must be `>= 0`. - `InitialBufferSize(size int)`: Sets the initial size of the internal ring buffer. Defaults to 32. Must be `>= 1`. ### Returns A new `Queue[T]` instance. ``` -------------------------------- ### Parse Period Range Source: https://github.com/domonda/go-types/blob/master/date/README.md Parses various period formats (year, month, quarter, week) into start and end dates. Useful for defining date ranges from shorthand inputs. ```go from, until, err := date.PeriodRange("2024-Q1") // from = "2024-01-01", until = "2024-03-31" ``` -------------------------------- ### PeriodRange Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/date.md Parses a period specification string into start and end dates (inclusive). Supports various formats like full year, year-month, quarter, half year, and ISO week. ```APIDOC ## PeriodRange ### Description Parses a period specification and returns the start and end dates (inclusive). ### Method Go Function ### Signature `func PeriodRange(str string) (from, until Date, err error)` ### Parameters #### Path Parameters - **str** (string) - Required - The period specification string. ### Accepted Period Formats: | Format | Example | |---|---| | Full year | `2024` | | Year-month | `2024-06` | | Quarter | `2024-Q1` | | Half year | `2024-H2` | | ISO week | `2024-W23` | ### Example ```go from, until, _ := date.PeriodRange("2024-Q1") // from = "2024-01-01", until = "2024-03-31" ``` ``` -------------------------------- ### Create Date Finder Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/date.md Creates a date finder configured for a specific language, useful for parsing dates with locale-specific formats. ```go func NewFinder(lang language.Code) *Finder ``` -------------------------------- ### Import Generic Set Helpers Source: https://github.com/domonda/go-types/blob/master/set/README.md Import the generic set helper package for use in your Go project. ```go import "github.com/domonda/go-types/set" ``` -------------------------------- ### Finder.FindAllIndex Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/main-types.md Finds all occurrences of a pattern within a byte slice. It returns a slice of `[start, end]` index pairs for each match found. The `n` parameter controls the maximum number of matches to return. ```APIDOC ## FindAllIndex ### Description Finds all occurrences of a pattern in a byte slice. ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | str | `[]byte` | The byte slice to search | | n | `int` | Match limit: -1 = all, 0 = none, >0 = at most n | ### Returns Slice of `[start, end]` index pairs for each match. ``` -------------------------------- ### Import Email Package Source: https://github.com/domonda/go-types/blob/master/email/README.md Import the go-types email package for use in your project. ```go import "github.com/domonda/go-types/email" ``` -------------------------------- ### Parse Period Range Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/date.md Parses a period specification string into start and end dates. Supports various formats like full year, year-month, quarter, half year, and ISO week. ```go from, until, _ := date.PeriodRange("2024-Q1") // from = "2024-01-01", until = "2024-03-31" ``` -------------------------------- ### Import Money Package Source: https://github.com/domonda/go-types/blob/master/money/README.md Import the money package to use its functionalities. ```go import "github.com/domonda/go-types/money" ``` -------------------------------- ### Get Default Value from Generic Nullable Type Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/nullable.md Illustrates using the GetOr() method to retrieve the wrapped value or a specified default if the nullable type is null. This provides a concise way to handle nulls. ```go n := nullable.New[string]() s := n.GetOr("default") // "default" ``` -------------------------------- ### Import strfmt Package Source: https://github.com/domonda/go-types/blob/master/strfmt/README.md Import the strfmt package to use its scanning and formatting functionalities. ```go import "github.com/domonda/go-types/strfmt" ``` -------------------------------- ### Import Language Package Source: https://github.com/domonda/go-types/blob/master/language/README.md Import the language package to use its functionalities. ```go import "github.com/domonda/go-types/language" ``` -------------------------------- ### Find Date Indices in Byte Slice Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/date.md Scans a byte slice for date-shaped substrings between word boundaries, using a language hint for format parsing. Returns a slice of start and end indices for each found date. ```go func (f *Finder) FindAllIndex(str []byte, n int) [][]int ``` ```go f := date.NewFinder(language.DE) for _, idx := range f.FindAllIndex(text, -1) { fmt.Println(string(text[idx[0]:idx[1]])) } ``` -------------------------------- ### Generic Nullable Type[T] Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/nullable.md The generic nullable wrapper Type[T] handles SQL NULL semantics where the zero value of type T represents NULL. It provides methods for getting, setting, and checking the null status of the wrapped value. ```APIDOC ## Generic Nullable Type[T] A generic nullable wrapper where the zero value of type T represents a NULL value. ### Constructors - `New[T any]() Type[T]` - Create null - `NewPtr[T any](ptr *T) Type[T]` - From pointer (nil → null) - `Of[T any](value T) Type[T]` - From value - `TypeFrom[T any](value T) Type[T]` - Explicit constructor - `TypeFromPtr[T any](ptr *T) Type[T]` - From pointer ### Methods #### Value ```go func (t Type[T]) Value() T ``` Returns the wrapped value or the zero value of T if null. #### Get ```go func (t Type[T]) Get() (T, bool) ``` Returns the wrapped value and whether it's non-null. Returns `(value, isNotNull)` tuple. **Example:** ```go n := nullable.Of(42) val, ok := n.Get() if ok { fmt.Println(val) // 42 } nullVal := nullable.New[int]() _, ok = nullVal.Get() // ok == false ``` #### IsNull ```go func (t Type[T]) IsNull() bool ``` Returns true if the value is null. #### IsNotNull ```go func (t Type[T]) IsNotNull() bool ``` Returns true if the value is not null. #### Set ```go func (t *Type[T]) Set(value T) ``` Sets the wrapped value to non-null. #### SetNull ```go func (t *Type[T]) SetNull() ``` Sets the value to null. **Example:** ```go n := nullable.Of(42) n.SetNull() // n.IsNull() == true ``` #### GetOr ```go func (t Type[T]) GetOr(def T) T ``` Returns the wrapped value if not null, otherwise the default. **Example:** ```go n := nullable.New[string]() s := n.GetOr("default") // "default" ``` ``` -------------------------------- ### Create New Queue with Custom Configuration Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/queue.md Creates a new unbounded FIFO queue with custom channel length and initial buffer size. ```go // Custom configuration q := queue.New[string]( queue.ChanLen(64), queue.InitialBufferSize(128), ) ``` -------------------------------- ### Set Union Operation Source: https://github.com/domonda/go-types/blob/master/_autodocs/README.md Demonstrates creating a set and performing a union operation with another set. ```go set1 := types.NewSet(1, 2, 3) set2 := types.NewSet(2, 3, 4) union := set1.Union(set2) ``` -------------------------------- ### Creating Nullable Types with Functional Options Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/nullable.md Illustrates different ways to create nullable types using the functional options pattern. This includes creating a null value, a value from a non-nil string, and a value from a pointer (where nil pointers result in null values). ```Go // Create null n := nullable.New[string]() // Create with value n := nullable.Of("hello") // Create from pointer (nil → null) var ptr *string n := nullable.TypeFromPtr(ptr) // Get value with default val := n.GetOr("default") ``` -------------------------------- ### Queue Interface Definition Source: https://github.com/domonda/go-types/blob/master/queue/README.md Defines the `Queue` interface with methods for adding items, accessing the consumer channel, checking length and capacity, and closing the queue. Also shows available configuration options. ```go type Queue[T any] interface { Add(items ...T) Next() <-chan T Len() int Cap() int Close() } func New[T any](options ...Option) // Options type ChanLen int // consumer-channel capacity type InitialBufferSize int // initial ring-buffer capacity ``` -------------------------------- ### JSON Marshaling and Unmarshaling VAT IDs Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/vat.md Demonstrates how to marshal and unmarshal VAT IDs to and from JSON strings. Also shows integration with database scanning and execution. ```Go var id vat.ID err := json.Unmarshal([]byte(`"DE123456789"`), &id) // id = "DE123456789" data, _ := json.Marshal(id) // data = "DE123456789" // Database var id vat.ID row.Scan(&id) db.Exec("INSERT INTO customers (vat_id) VALUES (?)", id) ``` -------------------------------- ### Set Operations with go-types Source: https://github.com/domonda/go-types/blob/master/README.md Demonstrates creating and performing union, intersection, and difference operations on sets using the go-types library. The results are printed in sorted order. ```go 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()) } ``` -------------------------------- ### Faster Date Parsing with Language Hints Source: https://github.com/domonda/go-types/blob/master/_autodocs/configuration.md Speed up date parsing by providing explicit language hints to the date.Normalize function, avoiding slower format detection. ```go d, _ := date.Normalize("05/06/2024", language.EN) // Faster d, _ := date.Normalize("05/06/2024") // Tries multiple formats ``` -------------------------------- ### Convenience CurrencyAmount Constructors Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/money.md Provides convenience constructors for creating CurrencyAmount objects for common currencies like USD, EUR, CHF, GBP, and JPY. ```go func CurrencyAmountUSD(amount Amount) CurrencyAmount func CurrencyAmountEUR(amount Amount) CurrencyAmount func CurrencyAmountCHF(amount Amount) CurrencyAmount func CurrencyAmountGBP(amount Amount) CurrencyAmount func CurrencyAmountJPY(amount Amount) CurrencyAmount ``` ```go ca := money.CurrencyAmountUSD(99.99) ``` -------------------------------- ### JSON Marshaling and Unmarshaling for IBAN Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/bank.md Demonstrates how to unmarshal a JSON string into an IBAN type and marshal an IBAN type back into a JSON string. Ensure the input JSON string is a valid IBAN format. ```go var iban bank.IBAN err := json.Unmarshal([]byte(`"DE89370400440532013000"`), &iban) // iban = "DE89370400440532013000" data, _ := json.Marshal(iban) // data = `"DE89370400440532013000"` ``` -------------------------------- ### JSON Marshaling and Unmarshaling of Sets Source: https://github.com/domonda/go-types/blob/master/README.md Shows how to marshal a set into JSON format and unmarshal JSON data back into a set. ```go 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()) } ``` -------------------------------- ### Create New Address Set Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/email.md Creates a new AddressSet from a variadic list of addresses, automatically deduplicating them. ```go func NewAddressSet(addrs ...Address) AddressSet ``` -------------------------------- ### StringSet Methods Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/account-charset-float.md Provides methods to create, add, check for containment, and delete strings from a StringSet. ```go func NewStringSet(strs ...string) StringSet ``` ```go func (s StringSet) Add(str string) ``` ```go func (s StringSet) Contains(str string) bool ``` ```go func (s StringSet) Delete(str string) ``` -------------------------------- ### Manage Per-Key Mutexes with StrMutex Source: https://github.com/domonda/go-types/blob/master/strutil/README.md Illustrates using StrMutex to manage a pool of mutexes keyed by strings, useful for serializing concurrent operations on specific keys without pre-allocating all mutexes. ```go locks := strutil.NewStrMutex() locks.Lock("user-42") defer locks.Unlock("user-42") ``` -------------------------------- ### Locale Presets for Formatting Source: https://github.com/domonda/go-types/blob/master/strfmt/README.md Provides functions to create English and German locale presets for formatting, including date formats and number separators. ```go strfmt.NewEnglishFormatConfig() // "02/01/2006", yes/no, dot decimal, comma thousands strfmt.NewGermanFormatConfig() // "02.01.2006", ja/nein, comma decimal, dot thousands ``` -------------------------------- ### Parse Dates with Language-Aware Month Names Source: https://github.com/domonda/go-types/blob/master/_autodocs/configuration.md Use `date.Normalize` with language hints to parse month names and abbreviations in different languages. ```go // German month abbreviations d, err := date.Normalize("5. Dez. 2024", language.DE) // English month names with language hint d, err := date.Normalize("Dec 5, 2024", language.EN) ``` -------------------------------- ### Float and Money Formatting Helpers Source: https://github.com/domonda/go-types/blob/master/strfmt/README.md Helper functions for creating specific float and money format definitions for English and German locales. ```go EnglishFloatFormat(precision) GermanFloatFormat(precision) EnglishMoneyFormat(currencyFirst) GermanMoneyFormat(currencyFirst) ``` -------------------------------- ### Concurrent Queue Operations Source: https://github.com/domonda/go-types/blob/master/_autodocs/README.md Shows the creation and usage of a concurrent FIFO queue with a specified channel length, and how to process items from it. ```go // Concurrent queue q := queue.New[string](queue.ChanLen(100)) q.Add("item1", "item2") for item := range q.Next() { // Process item } ``` -------------------------------- ### Amount Ptr Method Source: https://github.com/domonda/go-types/blob/master/_autodocs/api-reference/money.md Returns a pointer to a new copy of the Amount. ```go func (a Amount) Ptr() *Amount ```