Documentation
ΒΆ
Overview ΒΆ
Package cat provides efficient and flexible string concatenation utilities. It includes optimized functions for concatenating various types, builders for fluent chaining, and configuration options for defaults, pooling, and unsafe optimizations. The package aims to minimize allocations and improve performance in string building scenarios.
Index ΒΆ
- func And(conditions ...any) string
- func Append(dst []byte, args ...any) []byte
- func AppendBytes(dst []byte, args ...[]byte) []byte
- func AppendStrings(b *strings.Builder, ss ...string)
- func AppendTo(b *strings.Builder, args ...any)
- func AppendWith(sep string, dst []byte, args ...any) []byte
- func As(expression, alias string) string
- func Avg(column string, alias ...string) string
- func Between(x, y any, args ...any) string
- func BetweenWith(sep string, x, y any, args ...any) string
- func CSV(args ...any) string
- func Case(expression string, alias ...string) string
- func CaseWhen(conditionPart string, conditionValue, thenValue, elseValue any, ...) string
- func CaseWhenMulti(conditionParts []string, conditionValues, thenValues []any, elseValue any, ...) string
- func Comma(args ...any) string
- func Concat(args ...any) string
- func ConcatWith(sep string, args ...any) string
- func Count(column string, alias ...string) string
- func CountAll(alias ...string) string
- func Dot(args ...any) string
- func Flatten(args ...any) string
- func FlattenWith(sep string, args ...any) string
- func Group(groups ...[]any) string
- func GroupWith(sep string, groups ...[]any) string
- func In(column string, values ...string) string
- func Indent(depth int, args ...any) string
- func IsDeterministicMaps() bool
- func IsUnsafeBytes() bool
- func Join(elems ...string) string
- func JoinWith(sep string, elems ...string) string
- func Lines(args ...any) string
- func Max(column string, alias ...string) string
- func Min(column string, alias ...string) string
- func Number[T Numeric](a ...T) string
- func NumberWith[T Numeric](sep string, a ...T) string
- func On(table1, column1, table2, column2 string) string
- func Pad(s string) string
- func PadWith(sep, s string) string
- func Pair(a, b any) string
- func PairWith(sep string, a, b any) string
- func Parens(content string) string
- func ParensWith(sep string, args ...any) string
- func Path(args ...any) string
- func Pool(enable bool)
- func Prefix(p any, args ...any) string
- func PrefixEach(p any, sep string, args ...any) string
- func PrefixWith(sep string, p any, args ...any) string
- func Quote(args ...any) string
- func QuoteWith(quote byte, args ...any) string
- func Reflect(r reflect.Value) string
- func Repeat(val any, n int) string
- func RepeatWith(sep string, val any, n int) string
- func SetDeterministicMaps(enable bool)
- func SetUnsafeBytes(enable bool)
- func Space(args ...any) string
- func Sprint(args ...any) string
- func Suffix(s any, args ...any) string
- func SuffixEach(s any, sep string, args ...any) string
- func SuffixWith(sep string, s any, args ...any) string
- func Sum(column string, alias ...string) string
- func Trio(a, b, c any) string
- func TrioWith(sep string, a, b, c any) string
- func Using(alias1, column1, alias2, column2 string) string
- func With(sep string, args ...any) string
- func Wrap(before, after string, args ...any) string
- func WrapEach(before, after string, args ...any) string
- func WrapWith(sep, before, after string, args ...any) string
- type Builder
- type Numeric
Constants ΒΆ
This section is empty.
Variables ΒΆ
This section is empty.
Functions ΒΆ
func And ΒΆ
And joins multiple SQL conditions with the AND operator. Adds spacing to ensure clean SQL output (e.g., "cond1 AND cond2"). Accepts variadic arguments for flexible condition chaining.
func Append ΒΆ
Append appends args to dst and returns the grown slice. Callers can reuse dst across calls to amortize allocs. It uses an internal Builder for efficient concatenation of the args (no separators), then appends the result to the dst byte slice. Preallocates based on a size estimate to minimize reallocations. Benefits from Builder pooling if enabled. Useful for building byte slices incrementally without separators.
func AppendBytes ΒΆ
AppendBytes joins byte slices without separators. Only for compatibility with low-level byte processing. Directly appends each []byte arg to dst without any conversion or separators. Efficient for pure byte concatenation; no allocations if dst has capacity. Returns the extended dst slice. Does not use Builder, as it's simple append operations.
func AppendStrings ΒΆ
AppendStrings writes strings to an existing strings.Builder. Directly writes each string arg to the provided strings.Builder. No type checks or conversions; assumes all args are strings. Efficient for appending known strings without separators. Does not use cat.Builder, as it appends to an existing strings.Builder.
func AppendTo ΒΆ
AppendTo writes arguments to an existing strings.Builder. More efficient than creating new builders. Appends each arg to the provided strings.Builder using the optimized write function. No separators are added; for direct concatenation. Useful when you already have a strings.Builder and want to add more values efficiently. Does not use cat.Builder, as it appends to an existing strings.Builder.
func AppendWith ΒΆ
AppendWith appends args to dst and returns the grown slice. Callers can reuse dst across calls to amortize allocs. Similar to Append, but inserts the specified sep between each arg. Preallocates based on a size estimate including separators. Benefits from Builder pooling if enabled. Useful for building byte slices incrementally with custom separators.
func As ΒΆ
As creates an aliased SQL expression Example: As("COUNT(*)", "total_count") β "COUNT(*) AS total_count"
func Avg ΒΆ
Avg creates an AVG expression with optional alias Example: Avg("score") β "AVG(score)" Example: Avg("score", "average") β "AVG(score) AS average"
func Between ΒΆ
Between concatenates values wrapped between x and y (no separator between args). Equivalent to BetweenWith with an empty separator.
func BetweenWith ΒΆ
BetweenWith concatenates values wrapped between x and y, using sep between x, args, and y. Uses a pooled Builder if enabled; releases it after use. Equivalent to With(sep, x, args..., y).
func CSV ΒΆ
CSV joins arguments with "," separators (no space). Convenience wrapper for With using a comma as separator. Useful for simple CSV string generation without spaces.
func Case ΒΆ
Case creates a SQL CASE expression with optional alias Example: Case("WHEN status = 'active' THEN 1 ELSE 0 END", "is_active") β "CASE WHEN status = 'active' THEN 1 ELSE 0 END AS is_active"
func CaseWhen ΒΆ
func CaseWhen(conditionPart string, conditionValue, thenValue, elseValue any, alias ...string) string
CaseWhen creates a complete SQL CASE expression from individual parts with proper value handling Example: CaseWhen("status =", "'active'", "1", "0", "is_active") β "CASE WHEN status = 'active' THEN 1 ELSE 0 END AS is_active" Example: CaseWhen("age >", "18", "'adult'", "'minor'", "age_group") β "CASE WHEN age > 18 THEN 'adult' ELSE 'minor' END AS age_group"
func CaseWhenMulti ΒΆ
func CaseWhenMulti(conditionParts []string, conditionValues, thenValues []any, elseValue any, alias ...string) string
CaseWhenMulti creates a SQL CASE expression with multiple WHEN clauses Example: CaseWhenMulti([]string{"status =", "age >"}, []any{"'active'", 18}, []any{1, "'adult'"}, 0, "result") β "CASE WHEN status = 'active' THEN 1 WHEN age > 18 THEN 'adult' ELSE 0 END AS result"
func Comma ΒΆ
Comma joins arguments with ", " separators. Convenience wrapper for With using ", " as separator. Useful for human-readable lists with comma and space.
func Concat ΒΆ
Concat concatenates any values (no separators). Usage: cat.Concat("a", 1, true) β "a1true" Equivalent to With with an empty separator.
func ConcatWith ΒΆ
ConcatWith concatenates any values with separator. Alias for With; joins args with the provided sep.
func Count ΒΆ
Count creates a COUNT expression with optional alias Example: Count("id") β "COUNT(id)" Example: Count("id", "total") β "COUNT(id) AS total" Example: Count("DISTINCT user_id", "unique_users") β "COUNT(DISTINCT user_id) AS unique_users"
func CountAll ΒΆ
CountAll creates COUNT(*) with optional alias Example: CountAll() β "COUNT(*)" Example: CountAll("total") β "COUNT(*) AS total"
func Dot ΒΆ
Dot concatenates arguments with dot separators. Convenience for With using " " as separator.
func Flatten ΒΆ
Flatten joins nested values into a single concatenation using empty. Convenience for FlattenWith using empty.
func FlattenWith ΒΆ
FlattenWith joins nested values into a single concatenation with sep, avoiding intermediate slice allocations where possible. It recursively flattens any nested []any arguments, concatenating all leaf items with sep between them. Skips empty nested slices to avoid extra separators. Leaf items (non-slices) are converted using the optimized write function. Uses a pooled Builder if enabled; releases it after use. Preallocates based on a recursive estimate for efficiency. Example: FlattenWith(",", 1, []any{2, []any{3,4}}, 5) β "1,2,3,4,5"
func Group ΒΆ
Group joins multiple groups with empty between groups (no intra-group separators). Convenience for GroupWith using empty.
func GroupWith ΒΆ
GroupWith joins multiple groups with a separator between groups (no intra-group separators). Concatenates each group internally without separators, then joins non-empty groups with sep. Preestimates total size for allocation; uses pooled Builder if enabled. Optimized for single group: direct Concat. Useful for grouping related items with inter-group separation.
func In ΒΆ
In creates a SQL IN clause with properly quoted values Example: In("status", "active", "pending") β "status IN ('active', 'pending')" Handles value quoting and comma separation automatically
func Indent ΒΆ
Indent prefixes the concatenation of args with depth levels of two spaces per level. Example: Indent(2, "hello") => " hello" If depth <= 0, equivalent to Concat(args...). Uses " " repeated depth times as prefix, followed by concatenated args (no separators). Benefits from pooling via Concat.
func IsDeterministicMaps ΒΆ
func IsDeterministicMaps() bool
IsDeterministicMaps returns current map sorting setting. Thread-safe via atomic.Load. Returns true if deterministic sorting is enabled, false otherwise.
func IsUnsafeBytes ΒΆ
func IsUnsafeBytes() bool
IsUnsafeBytes reports whether zero-copy []byte -> string is enabled. Thread-safe via atomic.Load. Returns true if flag is 1, false otherwise. Useful for checking current configuration.
func Join ΒΆ
Join joins strings (matches stdlib strings.Join behavior). Usage: cat.Join("a", "b") β "a b" (using empty) Joins the variadic string args with the current empty. Useful for compatibility with stdlib but using package default sep.
func JoinWith ΒΆ
JoinWith joins strings with separator (variadic version). Directly uses strings.Join on the variadic string args with sep. Efficient for known strings; no conversions needed.
func Lines ΒΆ
Lines joins arguments with newline separators. Convenience for With using "\n" as separator. Useful for building multi-line strings.
func Max ΒΆ
Max creates a MAX expression with optional alias Example: Max("price") β "MAX(price)" Example: Max("price", "max_price") β "MAX(price) AS max_price"
func Min ΒΆ
Min creates a MIN expression with optional alias Example: Min("price") β "MIN(price)" Example: Min("price", "min_price") β "MIN(price) AS min_price"
func Number ΒΆ
Number concatenates numeric values without separators. Generic over Numeric types. Equivalent to NumberWith with empty sep.
func NumberWith ΒΆ
NumberWith concatenates numeric values with the provided separator. Generic over Numeric types. If no args, returns empty string. Uses pooled Builder if enabled, with rough growth estimate (8 bytes per item). Relies on valueToString for numeric conversion.
func On ΒΆ
On builds a SQL ON clause comparing two columns across tables. Formats as: "table1.column1 = table2.column2" with proper spacing. Useful in JOIN conditions to match keys between tables.
func Pad ΒΆ
Pad surrounds a string with spaces on both sides. Ensures proper spacing for SQL operators like "=", "AND", etc. Example: Pad("=") returns " = " for cleaner formatting.
func PadWith ΒΆ
PadWith adds a separator before the string and a space after it. Useful for formatting SQL parts with custom leading separators. Example: PadWith(",", "column") returns ",column ".
func PairWith ΒΆ
PairWith joins exactly two values with a separator. Optimized for two args: uses With(sep, a, b).
func Parens ΒΆ
Parens wraps content in parentheses Useful for grouping SQL conditions or expressions Example: Parens("a = b AND c = d") β "(a = b AND c = d)"
func ParensWith ΒΆ
ParensWith wraps multiple arguments in parentheses with a separator Example: ParensWith(" AND ", "a = b", "c = d") β "(a = b AND c = d)"
func Path ΒΆ
Path joins arguments with "/" separators. Convenience for With using "/" as separator. Useful for building file paths or URLs.
func Pool ΒΆ
func Pool(enable bool)
Pool enables or disables Builder pooling for New()/Release(). When enabled, you MUST call b.Release() after b.String() to return it. Thread-safe via atomic.Store. Enable for high-throughput scenarios to reduce allocations.
func Prefix ΒΆ
Prefix concatenates with a prefix (no separator). Equivalent to PrefixWith with empty sep.
func PrefixEach ΒΆ
PrefixEach applies the same prefix to each argument and joins the pairs with sep. Example: PrefixEach("pre-", ",", "a","b") => "pre-a,pre-b" Preestimates size including prefixes and seps. Uses pooled Builder if enabled; manually adds sep between pairs, no sep between p and a. Returns empty if no args.
func PrefixWith ΒΆ
PrefixWith concatenates with a prefix and separator. Adds p, then sep (if args present and sep not empty), then joins args with sep. Uses pooled Builder if enabled.
func Quote ΒΆ
Quote wraps each argument in double quotes, separated by spaces. Equivalent to QuoteWith with '"' as quote.
func QuoteWith ΒΆ
QuoteWith wraps each argument with the specified quote byte, separated by spaces. Wraps each arg with quote, writes arg, closes with quote; joins with space. Preestimates with quotes and spaces. Uses pooled Builder if enabled.
func Reflect ΒΆ
Reflect converts a reflect.Value to its string representation. It handles all kinds of reflected values including primitives, structs, slices, maps, etc. For nil values, it returns the nilString constant ("<nil>"). For unexported or inaccessible fields, it returns unexportedString ("<?>"). The output follows Go's syntax conventions where applicable (e.g., slices as [a, b], maps as {k:v}).
func Repeat ΒΆ
Repeat concatenates val n times (no sep between instances). Equivalent to RepeatWith with empty sep.
func RepeatWith ΒΆ
RepeatWith concatenates val n times with sep between each instance. If n <= 0, returns an empty string. Optimized to make exactly one allocation; converts val once. Uses pooled Builder if enabled.
func SetDeterministicMaps ΒΆ
func SetDeterministicMaps(enable bool)
SetDeterministicMaps controls whether map keys are sorted for deterministic output in reflection-based handling (e.g., in writeReflect for maps). When enabled, keys are sorted using a string-based comparison for consistent string representations. Thread-safe via atomic.Store. Useful for reproducible outputs in testing or logging.
func SetUnsafeBytes ΒΆ
func SetUnsafeBytes(enable bool)
SetUnsafeBytes toggles zero-copy []byte -> string conversions globally. When enabled, bytesToString uses unsafe.String for zero-allocation conversion. Thread-safe via atomic.Store. Use with caution: assumes the byte slice is not modified after conversion. Compatible with Go 1.20+; fallback to string(bts) if disabled.
func Space ΒΆ
Space concatenates arguments with space separators. Convenience for With using " " as separator.
func Sprint ΒΆ
Sprint concatenates any values (no separators). Usage: Sprint("a", 1, true) β "a1true" Equivalent to Concat or With with an empty separator.
func Suffix ΒΆ
Suffix concatenates with a suffix (no separator). Equivalent to SuffixWith with empty sep.
func SuffixEach ΒΆ
SuffixEach applies the same suffix to each argument and joins the pairs with sep. Example: SuffixEach("-suf", " | ", "a","b") => "a-suf | b-suf" Preestimates size including suffixes and seps. Uses pooled Builder if enabled; manually adds sep between pairs, no sep between a and s. Returns empty if no args.
func SuffixWith ΒΆ
SuffixWith concatenates with a suffix and separator. Joins args with sep, then adds sep (if args present and sep not empty), then s. Uses pooled Builder if enabled.
func Sum ΒΆ
Sum creates a SUM expression with optional alias Example: Sum("amount") β "SUM(amount)" Example: Sum("amount", "total") β "SUM(amount) AS total"
func TrioWith ΒΆ
TrioWith joins exactly three values with a separator. Optimized for three args: uses With(sep, a, b, c).
func Using ΒΆ
Using builds a SQL condition comparing two aliased columns. Formats as: "alias1.column1 = alias2.column2" for JOINs or filters. Helps when working with table aliases in complex queries.
func With ΒΆ
With concatenates arguments with the specified separator. Core concatenation function with sep. Optimized for zero or one arg: empty or direct valueToString. Fast path for all strings: exact preallocation, direct writes via raw strings.Builder (minimal branches/allocs). Fallback: pooled Builder with estimateWith, adds args with sep. Benefits from pooling if enabled for mixed types.
func Wrap ΒΆ
Wrap encloses concatenated args between before and after strings (no inner separator). Equivalent to Concat(before, args..., after).
func WrapEach ΒΆ
WrapEach wraps each argument individually with before/after, concatenated without separators. Applies before + arg + after to each arg. Preestimates size; uses pooled Builder if enabled. Returns empty if no args. Useful for wrapping multiple items identically without joins.
Types ΒΆ
type Builder ΒΆ
type Builder struct {
// contains filtered or unexported fields
}
Builder is a fluent concatenation helper. It is safe for concurrent use by multiple goroutines only if each goroutine uses a distinct *Builder. If pooling is enabled via Pool(true), call Release() when done. The Builder uses an internal strings.Builder for efficient string concatenation and manages a separator that is inserted between added values. It supports chaining methods for a fluent API style.
func New ΒΆ
New begins a new Builder with a separator. If pooling is enabled, the Builder is reused and MUST be released with b.Release() when done. If sep is empty, uses DefaultSep(). Optional initial arguments x are added immediately after creation. Pooling is controlled globally via Pool(true/false); when enabled, Builders are recycled to reduce allocations in high-throughput scenarios.
func Start ΒΆ
Start begins a new Builder with no separator (using an empty string as sep). It is a convenience function that wraps New(empty, x...), where empty is a constant empty string. This allows starting a concatenation without any separator between initial or subsequent additions. If pooling is enabled via Pool(true), the returned Builder MUST be released with b.Release() when done. Optional variadic arguments x are passed directly to New and added immediately after creation. Useful for fluent chains where no default separator is desired from the start.
func (*Builder) Add ΒΆ
Add appends values to the builder. It inserts the current separator before each new value if needed (i.e., after the first addition). Values are converted to strings using the optimized write function, which handles common types efficiently without allocations where possible. Supports any number of arguments of any type. Chains, returning the Builder for fluent use.
func (*Builder) Grow ΒΆ
Grow pre-sizes the internal buffer. This can be used to preallocate capacity based on an estimated total size, reducing reallocations during subsequent Add calls. It chains, returning the Builder for fluent use.
func (*Builder) If ΒΆ
If appends values to the builder only if the condition is true. Behaves like Add when condition is true; does nothing otherwise. Useful for conditional concatenation in chains. Chains, returning the Builder for fluent use.
func (*Builder) Output ΒΆ
Output returns the concatenated result and releases the Builder if pooling is enabled. This is a convenience method to get the string and clean up in one call. After Output, the Builder should not be used further if pooled, as it may be recycled. If pooling is disabled, it behaves like String without release.
func (*Builder) Release ΒΆ
func (b *Builder) Release()
Release returns the Builder to the pool if pooling is enabled. You should call this exactly once per New() when Pool(true) is active. Resets the internal state (buffer, separator, needsSep) before pooling to avoid retaining data or large allocations. If pooling is disabled, this is a no-op. Safe to call multiple times, but typically called once at the end of use.
type Numeric ΒΆ
type Numeric interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64
}
Numeric is a generic constraint interface for numeric types. It includes all signed/unsigned integers and floats. Used in generic functions like Number and NumberWith to constrain to numbers.