assign

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2025 License: MIT Imports: 11 Imported by: 3

README

assign

Go Reference Go Report Card Coverage Status Go Version

A powerful Go library for type conversion and value assignment with automatic type conversion, validation, and nil pointer initialization.

Features

  • Automatic Type Conversion: Seamlessly convert between compatible types (string ↔ int, float ↔ string, etc.)
  • Generic Type Safety: Leverage Go 1.18+ generics with type constraints for compile-time safety
  • Nil Pointer Handling: Automatically initialize nil pointers when needed
  • Interface Support: Built-in support for encoding.TextUnmarshaler and encoding.BinaryUnmarshaler
  • Extension System: Add custom type converters through extension functions
  • High Performance: Optimized fast paths for common type conversions
  • Comprehensive Time Parsing: Support for multiple time formats with intelligent layout detection
  • Zero Dependencies: Only depends on github.com/pkg/errors for enhanced error handling
  • Battle Tested: 95.2% test coverage with comprehensive edge case handling

Installation

go get github.com/slipros/assign@latest

Quick Start

package main

import (
    "fmt"
    "reflect"
    "time"

    "github.com/slipros/assign"
)

type User struct {
    ID       int       `json:"id"`
    Name     string    `json:"name"`
    Age      int       `json:"age"`
    IsActive bool      `json:"is_active"`
    JoinedAt time.Time `json:"joined_at"`
    Scores   []int     `json:"scores"`
}

func main() {
    var user User
    v := reflect.ValueOf(&user).Elem()

    // Convert string to int
    assign.Value(v.FieldByName("ID"), "123")

    // Set string directly
    assign.Value(v.FieldByName("Name"), "John Doe")

    // Convert string to int
    assign.Value(v.FieldByName("Age"), "30")

    // Convert string to bool
    assign.Value(v.FieldByName("IsActive"), "true")

    // Parse time from string
    assign.Value(v.FieldByName("JoinedAt"), "2023-01-15T10:30:00Z")

    // Convert string slice to int slice
    assign.SliceString(v.FieldByName("Scores"), []string{"85", "92", "78"})

    fmt.Printf("User: %+v\n", user)
    // Output: User: {ID:123 Name:John Doe Age:30 IsActive:true JoinedAt:2023-01-15 10:30:00 +0000 UTC Scores:[85 92 78]}
}

Core Functions

Value - Universal Assignment

The Value function is the primary entry point for type conversion and assignment:

func Value(to reflect.Value, from any, extensions ...ExtensionFunc) error

Example:

var target int
field := reflect.ValueOf(&target).Elem()

// Convert from various types
assign.Value(field, "42")        // string to int
assign.Value(field, 3.14)       // float to int
assign.Value(field, true)       // bool to int (true = 1)
assign.Value(field, []byte("5")) // []byte to int
Integer - Numeric Type Conversion
func Integer[I IntegerValue](to reflect.Value, from I) error

Supports all integer types with overflow protection:

var target int8
field := reflect.ValueOf(&target).Elem()

assign.Integer(field, 42)     // int to int8
assign.Integer(field, int64(100)) // int64 to int8

// Overflow protection
assign.Integer(field, 300)    // Returns error: value outside range
Float - Floating Point Conversion
func Float[F FloatValue](to reflect.Value, from F) error

Handles special float values (NaN, Infinity) appropriately:

var target float32
field := reflect.ValueOf(&target).Elem()

assign.Float(field, 3.14159)         // float64 to float32
assign.Float(field, math.Inf(1))     // Handles +Infinity
assign.Float(field, math.NaN())      // Handles NaN
String - Text Conversion
func String(to reflect.Value, from string) error

Optimized string parsing with fast paths for common types:

var targets struct {
    Number  int
    Active  bool
    Score   float64
    Items   []string
}

v := reflect.ValueOf(&targets).Elem()

assign.String(v.FieldByName("Number"), "123")
assign.String(v.FieldByName("Active"), "true")
assign.String(v.FieldByName("Score"), "95.5")
assign.String(v.FieldByName("Items"), "apple,banana,cherry") // CSV parsing
SliceString - Array and Slice Conversion
func SliceString(to reflect.Value, from []string, options ...SliceOptionFunc) error

Convert string slices to various types with configurable separators:

var intSlice []int
var joinedString string

field1 := reflect.ValueOf(&intSlice).Elem()
field2 := reflect.ValueOf(&joinedString).Elem()

// String slice to int slice
assign.SliceString(field1, []string{"1", "2", "3", "4"})

// String slice to joined string
assign.SliceString(field2, []string{"apple", "banana", "cherry"})
// Result: "apple,banana,cherry"

// Custom separator
assign.SliceString(field2, []string{"a", "b", "c"}, assign.WithSeparator(" | "))
// Result: "a | b | c"

Advanced Features

Extension Functions

Create custom type converters for specialized types:

// Custom type
type UserID int64

// Extension function for UserID conversion
func userIDExtension(value any) (func() error, bool) {
    str, ok := value.(string)
    if !ok || !strings.HasPrefix(str, "user:") {
        return nil, false
    }

    return func() error {
        idStr := strings.TrimPrefix(str, "user:")
        id, err := strconv.ParseInt(idStr, 10, 64)
        if err != nil {
            return err
        }
        *userID = UserID(id)
        return nil
    }, true
}

// Usage
var userID UserID
field := reflect.ValueOf(&userID).Elem()
assign.Value(field, "user:12345", userIDExtension)
Interface Support

Built-in support for standard Go interfaces:

// Custom type implementing TextUnmarshaler
type Email string

func (e *Email) UnmarshalText(text []byte) error {
    s := string(text)
    if !strings.Contains(s, "@") {
        return errors.New("invalid email format")
    }
    *e = Email(s)
    return nil
}

// Automatic interface detection
var email Email
field := reflect.ValueOf(&email).Elem()
assign.String(field, "[email protected]") // Uses UnmarshalText automatically
Time Parsing

Intelligent time parsing with multiple format support:

var timestamp time.Time
field := reflect.ValueOf(&timestamp).Elem()

// Supports multiple formats automatically
assign.String(field, "2023-01-15T10:30:00Z")       // RFC3339
assign.String(field, "2023-01-15")                 // Date only
assign.String(field, "01/15/2023")                 // US format
assign.String(field, "2023-01-15 10:30:00")        // DateTime

Type Constraints

The library uses Go 1.18+ generics with type constraints for compile-time safety:

// Integer constraints
type SignedValue interface {
    ~int | ~int8 | ~int16 | ~int32 | ~int64
}

type UnsignedValue interface {
    ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

type IntegerValue interface {
    SignedValue | UnsignedValue
}

// Float constraints
type FloatValue interface {
    ~float32 | ~float64
}

Error Handling

The library provides detailed error information for debugging:

var target int8
field := reflect.ValueOf(&target).Elem()

err := assign.Integer(field, 300) // Value too large for int8
if err != nil {
    fmt.Println(err) // "value 300 is outside the range of target type int8 [-128, 127]"
}

err = assign.String(field, "not_a_number")
if errors.Is(err, assign.ErrNotSupported) {
    fmt.Println("Conversion not supported")
}

Performance

The library is optimized for performance with:

  • Fast paths for common type conversions
  • Zero allocations for primitive type conversions
  • Compiled regex patterns for time format detection
  • Thread-safe caching for successful time format matches
  • Optimized string operations with minimal allocations

Real-World Example

Here's a practical example of using the library for configuration parsing:

package main

import (
    "fmt"
    "reflect"
    "strconv"
    "strings"

    "github.com/slipros/assign"
)

type Config struct {
    Host     string        `env:"HOST"`
    Port     int           `env:"PORT"`
    Debug    bool          `env:"DEBUG"`
    Timeout  time.Duration `env:"TIMEOUT"`
    Features []string      `env:"FEATURES"`
}

func parseConfig(envVars map[string]string) (*Config, error) {
    config := &Config{}
    v := reflect.ValueOf(config).Elem()
    t := v.Type()

    for i := 0; i < v.NumField(); i++ {
        field := v.Field(i)
        fieldType := t.Field(i)

        envTag := fieldType.Tag.Get("env")
        if envTag == "" {
            continue
        }

        envValue, exists := envVars[envTag]
        if !exists {
            continue
        }

        // Handle different field types
        switch fieldType.Type.String() {
        case "[]string":
            parts := strings.Split(envValue, ",")
            if err := assign.SliceString(field, parts); err != nil {
                return nil, err
            }
        case "time.Duration":
            // Custom extension for duration
            duration, err := time.ParseDuration(envValue)
            if err != nil {
                return nil, err
            }
            field.Set(reflect.ValueOf(duration))
        default:
            if err := assign.String(field, envValue); err != nil {
                return nil, err
            }
        }
    }

    return config, nil
}

func main() {
    envVars := map[string]string{
        "HOST":     "localhost",
        "PORT":     "8080",
        "DEBUG":    "true",
        "TIMEOUT":  "30s",
        "FEATURES": "auth,logging,metrics",
    }

    config, err := parseConfig(envVars)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Config: %+v\n", config)
}

Documentation


Made with ❤️ for the Go community

Documentation

Overview

Package assign provides utilities for type conversion and setting values in Go structs with automatic type conversion, validation, and nil pointer initialization.

The library offers seamless conversion between compatible types, supports Go 1.18+ generics with type constraints, and provides an extension system for custom type converters. It's designed for high performance with optimized fast paths for common conversions.

Example usage:

var target int
field := reflect.ValueOf(&target).Elem()
err := assign.Value(field, "42") // Converts string "42" to int 42

The library supports:

  • Automatic type conversion between compatible types
  • Generic type constraints for compile-time safety
  • Nil pointer initialization when needed
  • TextUnmarshaler and BinaryUnmarshaler interface support
  • Extension functions for custom type conversions
  • Optimized performance with fast paths for common types

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNotSupported = errors.New("not supported")

ErrNotSupported is returned when a type conversion is not supported. This error indicates that the source type cannot be converted to the target type using the available conversion functions.

Functions

func Float

func Float[F FloatValue](to reflect.Value, from F) error

Float converts a floating-point value to the appropriate type for a target field. Handles conversion to strings, booleans, numeric types, complex types, and interfaces. Special values (NaN, Infinity) are handled appropriately for each target type.

Parameters:

  • field: Target field to set (reflect.Value).
  • number: Floating-point value to convert and set.

Returns:

  • error: If conversion or assignment fails.
Example

ExampleFloat demonstrates floating-point conversion with special value handling.

package main

import (
	"fmt"
	"reflect"

	"github.com/slipros/assign"
)

func main() {
	var targets struct {
		Regular float32
		Double  float64
		Text    string
	}

	v := reflect.ValueOf(&targets).Elem()

	// Float conversions
	if err := assign.Float(v.FieldByName("Regular"), 3.14159); err != nil {
		panic(err)
	}
	if err := assign.Float(v.FieldByName("Double"), 2.71828182845); err != nil {
		panic(err)
	}

	// Float to string conversion
	if err := assign.Float(v.FieldByName("Text"), 123.456); err != nil {
		panic(err)
	}

	fmt.Printf("Regular: %.2f\n", targets.Regular)
	fmt.Printf("Double: %.5f\n", targets.Double)
	fmt.Printf("Text: %s\n", targets.Text)

}
Output:

Regular: 3.14
Double: 2.71828
Text: 123.456

func Integer

func Integer[I IntegerValue](to reflect.Value, from I) error

Integer converts an integer value to the appropriate type for a target field. Handles conversion to strings, booleans, numeric types, and interfaces. Performs range checking to prevent overflow.

Parameters:

  • field: Target field to set (reflect.Value).
  • number: Integer value to convert and set.

Returns:

  • error: If conversion or assignment fails.
Example

ExampleInteger demonstrates type-safe integer conversion with overflow protection and range checking.

package main

import (
	"fmt"
	"reflect"

	"github.com/slipros/assign"
)

func main() {
	var targets struct {
		Small  int8
		Medium int16
		Large  int64
	}

	v := reflect.ValueOf(&targets).Elem()

	// Safe conversions within range
	if err := assign.Integer(v.FieldByName("Small"), int(42)); err != nil {
		panic(err)
	}
	if err := assign.Integer(v.FieldByName("Medium"), int32(1000)); err != nil {
		panic(err)
	}
	if err := assign.Integer(v.FieldByName("Large"), int64(999999999)); err != nil {
		panic(err)
	}

	fmt.Printf("Small: %d\n", targets.Small)
	fmt.Printf("Medium: %d\n", targets.Medium)
	fmt.Printf("Large: %d\n", targets.Large)

}
Output:

Small: 42
Medium: 1000
Large: 999999999

func Pointer

func Pointer(value reflect.Value) (any, bool)

Pointer gets a pointer to the underlying value of a reflect.Value. Handles both existing pointers and non-pointer values that need addressing.

Parameters:

  • value: The reflect.Value to get a pointer to.

Returns:

  • any: A pointer to the value, or nil if not possible.
  • bool: Whether the operation was successful.

func SliceString

func SliceString(to reflect.Value, from []string, options ...SliceOptionFunc) error

SliceString converts a string slice to appropriate types for target fields. Handles conversions to strings (joins elements), numeric slices, boolean slices, and other compatible types.

Parameters:

  • field: Target field to set (reflect.Value).
  • arr: String slice to convert and set.
  • options: Optional settings like custom separator (default: ",").

Returns:

  • error: If conversion or assignment fails.
Example

ExampleSliceString demonstrates converting string slices to various types and joining them with custom separators.

package main

import (
	"fmt"
	"reflect"

	"github.com/slipros/assign"
)

func main() {
	var targets struct {
		Numbers []int
		Joined  string
		Custom  string
	}

	v := reflect.ValueOf(&targets).Elem()
	stringSlice := []string{"1", "2", "3", "4", "5"}

	// Convert to int slice
	if err := assign.SliceString(v.FieldByName("Numbers"), stringSlice); err != nil {
		panic(err)
	}

	// Join with default separator (comma)
	if err := assign.SliceString(v.FieldByName("Joined"), []string{"apple", "banana", "cherry"}); err != nil {
		panic(err)
	}

	// Join with custom separator
	if err := assign.SliceString(v.FieldByName("Custom"), []string{"red", "green", "blue"}, assign.WithSeparator(" | ")); err != nil {
		panic(err)
	}

	fmt.Printf("Numbers: %v\n", targets.Numbers)
	fmt.Printf("Joined: %s\n", targets.Joined)
	fmt.Printf("Custom: %s\n", targets.Custom)

}
Output:

Numbers: [1 2 3 4 5]
Joined: apple,banana,cherry
Custom: red | green | blue

func String

func String(to reflect.Value, from string) error

String converts a string value to the appropriate type for a target field. This is an optimized version that uses fast paths for common type conversions while maintaining full compatibility with all supported types. Handles conversion to numeric types, booleans, slices, time.Time and other types. Supports types implementing TextUnmarshaler or BinaryUnmarshaler interfaces.

Parameters:

  • field: Target field to set (reflect.Value).
  • str: String value to convert and set.

Returns:

  • error: If conversion or assignment fails.
Example

ExampleString demonstrates string parsing and conversion to various types including optimized fast paths for common conversions.

package main

import (
	"fmt"
	"reflect"

	"github.com/slipros/assign"
)

func main() {
	var targets struct {
		Number  int
		Active  bool
		Score   float64
		Items   []string
		Bytes   []byte
		Complex complex128
	}

	v := reflect.ValueOf(&targets).Elem()

	// String to various types
	if err := assign.String(v.FieldByName("Number"), "42"); err != nil {
		panic(err)
	}
	if err := assign.String(v.FieldByName("Active"), "true"); err != nil {
		panic(err)
	}
	if err := assign.String(v.FieldByName("Score"), "98.6"); err != nil {
		panic(err)
	}
	if err := assign.String(v.FieldByName("Items"), "apple,banana,cherry"); err != nil {
		panic(err)
	}
	if err := assign.String(v.FieldByName("Bytes"), "hello"); err != nil {
		panic(err)
	}
	if err := assign.String(v.FieldByName("Complex"), "3+4i"); err != nil {
		panic(err)
	}

	fmt.Printf("Number: %d\n", targets.Number)
	fmt.Printf("Active: %t\n", targets.Active)
	fmt.Printf("Score: %.1f\n", targets.Score)
	fmt.Printf("Items: %v\n", targets.Items)
	fmt.Printf("Bytes: %s\n", string(targets.Bytes))
	fmt.Printf("Complex: %v\n", targets.Complex)

}
Output:

Number: 42
Active: true
Score: 98.6
Items: [apple banana cherry]
Bytes: hello
Complex: (3+4i)
Example (BooleanConversions)

ExampleString_booleanConversions demonstrates various ways to convert strings to boolean values.

package main

import (
	"fmt"
	"reflect"

	"github.com/slipros/assign"
)

func main() {
	var results struct {
		A, B, C, D, E, F, G, H bool
	}

	v := reflect.ValueOf(&results).Elem()
	fields := []string{"A", "B", "C", "D", "E", "F", "G", "H"}
	values := []string{"true", "1", "yes", "on", "false", "0", "no", "off"}

	for i, value := range values {
		if err := assign.String(v.FieldByName(fields[i]), value); err != nil {
			panic(err)
		}
	}

	fmt.Printf("'true' -> %t\n", results.A)
	fmt.Printf("'1' -> %t\n", results.B)
	fmt.Printf("'yes' -> %t\n", results.C)
	fmt.Printf("'on' -> %t\n", results.D)
	fmt.Printf("'false' -> %t\n", results.E)
	fmt.Printf("'0' -> %t\n", results.F)
	fmt.Printf("'no' -> %t\n", results.G)
	fmt.Printf("'off' -> %t\n", results.H)

}
Output:

'true' -> true
'1' -> true
'yes' -> true
'on' -> true
'false' -> false
'0' -> false
'no' -> false
'off' -> false
Example (TimeConversion)

ExampleString_timeConversion demonstrates automatic time parsing with multiple format support.

package main

import (
	"fmt"
	"reflect"
	"time"

	"github.com/slipros/assign"
)

func main() {
	var timestamps struct {
		RFC3339  time.Time
		DateOnly time.Time
		DateTime time.Time
		USFormat time.Time
	}

	v := reflect.ValueOf(&timestamps).Elem()

	// Various time formats
	if err := assign.String(v.FieldByName("RFC3339"), "2023-01-15T10:30:00Z"); err != nil {
		panic(err)
	}
	if err := assign.String(v.FieldByName("DateOnly"), "2023-01-15"); err != nil {
		panic(err)
	}
	if err := assign.String(v.FieldByName("DateTime"), "2023-01-15 10:30:00"); err != nil {
		panic(err)
	}
	if err := assign.String(v.FieldByName("USFormat"), "01/15/2023"); err != nil {
		panic(err)
	}

	fmt.Printf("RFC3339: %s\n", timestamps.RFC3339.Format("2006-01-02 15:04:05"))
	fmt.Printf("DateOnly: %s\n", timestamps.DateOnly.Format("2006-01-02"))
	fmt.Printf("DateTime: %s\n", timestamps.DateTime.Format("2006-01-02 15:04:05"))
	fmt.Printf("USFormat: %s\n", timestamps.USFormat.Format("2006-01-02"))

}
Output:

RFC3339: 2023-01-15 10:30:00
DateOnly: 2023-01-15
DateTime: 2023-01-15 10:30:00
USFormat: 2023-01-15

func Value

func Value(to reflect.Value, from any, extensions ...ExtensionFunc) error

Value assigns a value to a reflect.Value field with automatic type conversion. This is the primary entry point for the assign library, handling initialization of nil pointers, various primitive types, and interfaces.

The function automatically determines the best conversion strategy based on the source and target types. Extension functions can be provided to handle custom type conversions that aren't built into the library.

Key features:

  • Converts between compatible types (string ↔ int, float ↔ string, etc.)
  • Initializes nil pointers when needed
  • Supports fmt.Stringer interface for string conversion
  • Handles slices, arrays, and common primitive types
  • Uses extension functions for custom type conversions
  • Provides detailed error messages for debugging

Example:

var target struct {
	ID   int
	Name string
	Age  *int
}
v := reflect.ValueOf(&target).Elem()

// Convert string to int
assign.Value(v.FieldByName("ID"), "123")

// Set string directly
assign.Value(v.FieldByName("Name"), "John")

// Initialize nil pointer and set value
assign.Value(v.FieldByName("Age"), "30")

Parameters:

  • to: Target field to set (must be settable reflect.Value)
  • from: Source value to convert and assign (any type)
  • extensions: Optional extension functions for custom type conversions

Returns:

  • error: If value could not be set due to type incompatibility or other issues
Example

ExampleValue demonstrates basic usage of the Value function for converting between different types.

package main

import (
	"fmt"
	"reflect"

	"github.com/slipros/assign"
)

func main() {
	var target struct {
		ID       int
		Name     string
		Age      *int
		IsActive bool
		Score    float64
	}

	v := reflect.ValueOf(&target).Elem()

	// Convert string to int
	if err := assign.Value(v.FieldByName("ID"), "123"); err != nil {
		panic(err)
	}

	// Set string directly
	if err := assign.Value(v.FieldByName("Name"), "John Doe"); err != nil {
		panic(err)
	}

	// Initialize nil pointer and set value
	if err := assign.Value(v.FieldByName("Age"), "30"); err != nil {
		panic(err)
	}

	// Convert string to bool
	if err := assign.Value(v.FieldByName("IsActive"), "true"); err != nil {
		panic(err)
	}

	// Convert string to float
	if err := assign.Value(v.FieldByName("Score"), "95.5"); err != nil {
		panic(err)
	}

	fmt.Printf("ID: %d\n", target.ID)
	fmt.Printf("Name: %s\n", target.Name)
	fmt.Printf("Age: %d\n", *target.Age)
	fmt.Printf("IsActive: %t\n", target.IsActive)
	fmt.Printf("Score: %.1f\n", target.Score)

}
Output:

ID: 123
Name: John Doe
Age: 30
IsActive: true
Score: 95.5
Example (ExtensionFunc)

ExampleValue_extensionFunc demonstrates how to create and use extension functions for custom type conversions.

package main

import (
	"fmt"
	"net/http"
	"reflect"

	"github.com/slipros/assign"
)

func main() {
	// Extension function for HTTP Cookie conversion
	cookieExtension := func(value any) (func(to reflect.Value) error, bool) {
		cookie, ok := value.(*http.Cookie)
		if !ok {
			return nil, false
		}

		return func(to reflect.Value) error {
			return assign.String(to, cookie.Value)
		}, true
	}

	// Create a sample cookie
	cookie := &http.Cookie{Name: "session", Value: "abc123def456"}
	var sessionID string
	field := reflect.ValueOf(&sessionID).Elem()

	// Use the extension function with assign.Value
	if err := assign.Value(field, cookie, cookieExtension); err != nil {
		panic(err)
	}

	fmt.Printf("Session ID: %s\n", sessionID)

}
Output:

Session ID: abc123def456
Example (NilPointers)

ExampleValue_nilPointers demonstrates automatic nil pointer initialization during value assignment.

package main

import (
	"fmt"
	"reflect"

	"github.com/slipros/assign"
)

func main() {
	var data struct {
		Name  *string
		Age   *int
		Score *float64
		Tags  *[]string
	}

	v := reflect.ValueOf(&data).Elem()

	// All fields start as nil, but assign will initialize them
	if err := assign.Value(v.FieldByName("Name"), "John"); err != nil {
		panic(err)
	}
	if err := assign.Value(v.FieldByName("Age"), "30"); err != nil {
		panic(err)
	}
	if err := assign.Value(v.FieldByName("Score"), "95.5"); err != nil {
		panic(err)
	}
	if err := assign.SliceString(v.FieldByName("Tags"), []string{"developer", "golang"}); err != nil {
		panic(err)
	}

	fmt.Printf("Name: %s\n", *data.Name)
	fmt.Printf("Age: %d\n", *data.Age)
	fmt.Printf("Score: %.1f\n", *data.Score)
	fmt.Printf("Tags: %v\n", *data.Tags)

}
Output:

Name: John
Age: 30
Score: 95.5
Tags: [developer golang]

Types

type ExtensionFunc

type ExtensionFunc func(any) (func(to reflect.Value) error, bool)

ExtensionFunc defines a function type for custom type conversion extensions. It takes a value of any type and returns a conversion function and a boolean indicating whether the conversion is supported.

The returned function performs the actual conversion and returns an error if it fails. The boolean indicates whether this extension can handle the given value type.

type FloatValue

type FloatValue interface {
	~float32 | ~float64
}

FloatValue is a constraint that permits any floating-point type. If future releases of Go add new predeclared floating-point types, this constraint will be modified to include them.

type IntegerValue

type IntegerValue interface {
	SignedValue | UnsignedValue
}

IntegerValue is a constraint that permits any integer type. If future releases of Go add new predeclared integer types, this constraint will be modified to include them.

type SignedValue

type SignedValue interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

SignedValue is a constraint that permits any signed integer type. If future releases of Go add new predeclared signed integer types, this constraint will be modified to include them.

type SliceOptionFunc

type SliceOptionFunc func(*sliceOptions)

SliceOptionFunc is a functional option for configuring SliceString behavior

func WithSeparator

func WithSeparator(sep string) SliceOptionFunc

WithSeparator sets a custom separator for joining string slices. Used as an option in SliceString.

Example: WithSeparator("|") // Join with pipe character

type UnsignedValue

type UnsignedValue interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

UnsignedValue is a constraint that permits any unsigned integer type. If future releases of Go add new predeclared unsigned integer types, this constraint will be modified to include them.

Jump to

Keyboard shortcuts

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