conv

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2026 License: GPL-3.0 Imports: 12 Imported by: 0

README

conv

conv is a powerful, flexible, and type-safe Go library for converting between different data types. It simplifies type conversions with support for primitives, slices, maps, structs, time values, and more.

Overview

The conv package provides a comprehensive set of functions to convert between Go types in a safe and predictable way. It handles edge cases like nil values, empty strings, overflow protection, and supports both strict and lenient conversion modes.

Key Features:

  • 🔄 Type-safe conversions using Go generics (To[T], Slice[T])
  • Fast-path optimizations for common types
  • 🛡️ Overflow protection for numeric conversions
  • 🔧 Configurable behavior (strict mode, custom date formats, nil/empty handling)
  • 📦 Rich API with Must*, *OrDefault, and error-returning variants
  • 🧩 Extensible via custom converter interfaces
  • ⏱️ Time parsing with multiple date format support
  • 🗂️ Collection conversions (slices, maps, structs)
  • 📝 JSON parsing helpers with generics

Use Cases

When to Use
  • ✅ Converting user input (strings) to typed values (int, bool, float)
  • ✅ Parsing configuration files or environment variables
  • ✅ Working with heterogeneous data from JSON/YAML
  • ✅ Building APIs that accept flexible input types
  • ✅ Type conversion in database query results
  • ✅ Normalizing data from external sources
When Not to Use
  • ❌ When you need complex validation logic (use a validation library instead)
  • ❌ When source types are already known at compile time (use type assertions)
  • ❌ For performance-critical hot paths with known types (use native conversions)
  • ❌ When you need bidirectional serialization (use encoding packages)

Installation

go get github.com/sivaosorg/replify

Import the package in your Go code:

import "github.com/sivaosorg/replify/pkg/conv"

Usage

Basic Conversions

The package provides simple functions for converting between common types:

package main

import (
    "fmt"
    "github.com/sivaosorg/replify/pkg/conv"
)

func main() {
    // String to integer
    num, err := conv.Int("42")
    if err != nil {
        panic(err)
    }
    fmt.Println(num) // 42

    // String to boolean
    flag, _ := conv.Bool("true")
    fmt.Println(flag) // true

    // Integer to string
    str, _ := conv.String(12345)
    fmt.Println(str) // "12345"

    // Float to integer (with truncation)
    intVal, _ := conv.Int(3.14)
    fmt.Println(intVal) // 3
}
Generic Type Conversion

Use the generic To[T] function for type-safe conversions:

// Convert to specific types using generics
age, err := conv.To[int]("25")
price, err := conv.To[float64]("19.99")
name, err := conv.To[string](12345)
active, err := conv.To[bool]("yes")

// All return the correct type without casting
fmt.Printf("%T: %v\n", age, age)       // int: 25
fmt.Printf("%T: %v\n", price, price)   // float64: 19.99
Must and OrDefault Variants

For cleaner code when you're confident about conversion or want fallbacks:

// Must* functions panic on error (use in initialization)
count := conv.MustInt("100")
timeout := conv.MustDuration("30s")

// *OrDefault functions return a default value on error
port := conv.IntOrDefault(os.Getenv("PORT"), 8080)
debug := conv.BoolOrDefault(os.Getenv("DEBUG"), false)
maxRetry := conv.Int64OrDefault(config["max_retry"], 3)
Type Inference

The Infer function automatically converts values to the target type:

var age int
err := conv.Infer(&age, "42")
fmt.Println(age) // 42

var duration time.Duration
err = conv.Infer(&duration, "1h30m")
fmt.Println(duration) // 1h30m0s

var timestamp time.Time
err = conv.Infer(&timestamp, "2024-01-15T10:00:00Z")
fmt.Println(timestamp) // 2024-01-15 10:00:00 +0000 UTC

Examples

1. Converting Strings to Numbers
// String to various numeric types
i, _ := conv.Int("123")           // int: 123
i8, _ := conv.Int8("127")         // int8: 127
i16, _ := conv.Int16("32000")     // int16: 32000
i32, _ := conv.Int32("2000000")   // int32: 2000000
i64, _ := conv.Int64("9000000")   // int64: 9000000

// Unsigned integers
u, _ := conv.Uint("12345")        // uint: 12345
u8, _ := conv.Uint8("255")        // uint8: 255
u64, _ := conv.Uint64("9876543210") // uint64: 9876543210

// Floating-point
f32, _ := conv.Float32("3.14")    // float32: 3.14
f64, _ := conv.Float64("2.71828") // float64: 2.71828
2. Boolean Conversions
// Flexible boolean parsing
conv.Bool("true")   // true
conv.Bool("1")      // true
conv.Bool("yes")    // true
conv.Bool("Y")      // true

conv.Bool("false")  // false
conv.Bool("0")      // false
conv.Bool("no")     // false
conv.Bool("N")      // false

// Numeric to boolean
conv.Bool(1)        // true
conv.Bool(0)        // false
conv.Bool(42)       // true (non-zero)
3. Time and Duration Conversions
// Parse durations
d1, _ := conv.Duration("2h45m")       // 2h45m0s
d2, _ := conv.Duration("1.5")         // 1.5s (float seconds)
d3, _ := conv.Duration(5000000000)    // 5s (nanoseconds)

// Parse dates/times
t1, _ := conv.Time("2024-01-15T10:00:00Z")
t2, _ := conv.Time("2024-01-15")
t3, _ := conv.Time(1705320000)        // Unix timestamp

// Duration helpers
dur := conv.Seconds(90)               // 1m30s
dur = conv.Minutes(2.5)               // 2m30s
dur = conv.Hours(1.5)                 // 1h30m0s
dur = conv.Days(7)                    // 168h0m0s
4. Slice Conversions
// Convert to typed slices
ints, _ := conv.IntSlice([]any{"1", 2, 3.0})
// []int{1, 2, 3}

floats, _ := conv.Float64Slice([]any{1, "2.5", 3.14})
// []float64{1.0, 2.5, 3.14}

strs, _ := conv.StringSlice([]any{1, 2, 3})
// []string{"1", "2", "3"}

// Generic slice conversion
nums, _ := conv.Slice[int]([]string{"10", "20", "30"})
// []int{10, 20, 30}

// With default fallback
result := conv.SliceOrDefault[int]("invalid", []int{1, 2, 3})
// []int{1, 2, 3}
5. Map Conversions
// Struct to map
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

user := User{Name: "Alice", Age: 30}
m, _ := conv.MapTo(user)
// map[string]any{"name": "Alice", "age": 30}

// Typed map conversions
strMap, _ := conv.StringMap(m)
// map[string]string{"name": "Alice", "age": "30"}

intMap, _ := conv.IntMap(map[string]any{"a": "1", "b": 2})
// map[string]int{"a": 1, "b": 2}

boolMap, _ := conv.BoolMap(map[string]any{"active": "true", "debug": 1})
// map[string]bool{"active": true, "debug": true}
6. JSON Parsing
type Config struct {
    Host string `json:"host"`
    Port int    `json:"port"`
}

jsonStr := `{"host": "localhost", "port": 8080}`

// Parse with error handling
var cfg Config
err := conv.FromJSON(jsonStr, &cfg)

// Generic parsing
cfg, err := conv.ParseJSON[Config](jsonStr)

// Must variant (panics on error)
cfg := conv.MustParseJSON[Config](jsonStr)

// From bytes
data := []byte(jsonStr)
cfg, _ := conv.ParseJSONBytes[Config](data)

// Deep copy using JSON
clone, _ := conv.Clone(cfg)
7. Custom Converter Configuration
// Create a custom converter
c := conv.NewConverter().
    WithStrictMode(true).               // Error on lossy conversions
    WithTrimStrings(true).              // Trim whitespace
    WithNilAsZero(false).               // Nil returns error
    WithEmptyAsZero(false).             // Empty string returns error
    WithDateFormats("2006-01-02", "02/01/2006")

// Use custom converter
value, err := c.Int("  42  ")           // Uses trimStrings
date, err := c.Time("15/01/2024")       // Uses custom date formats

// Clone and modify
c2 := c.Clone().WithStrictMode(false)

API Reference

Core Conversion Functions
Function Description Example
To[T](from any) Generic type conversion conv.To[int]("42")
MustTo[T](from any) Panics on error conv.MustTo[bool]("true")
ToOrDefault[T](from, default) Returns default on error conv.ToOrDefault[int]("x", 0)
Infer(&into, from) Infers target type conv.Infer(&age, "25")
Primitive Types

Integers: Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64

Floats: Float32, Float64

Boolean: Bool, BoolOrDefault, MustBool

String: String, StringOrDefault, MustString

Time: Time, Duration, TimeOrDefault, DurationOrDefault

Collections

Slices:

  • Slice[T](from) - Generic slice conversion
  • IntSlice, Int64Slice, Float64Slice, StringSlice, BoolSlice
  • SliceOrDefault[T](from, default)

Maps:

  • MapTo(from) - Convert to map[string]any
  • StringMap, IntMap, Float64Map, BoolMap
JSON Utilities
  • FromJSON(jsonStr, &target) - Parse JSON string
  • ParseJSON[T](jsonStr) - Generic JSON parsing
  • MustParseJSON[T](jsonStr) - Panics on error
  • Clone[T](value) - Deep copy via JSON
Special Functions
  • IsNaN(from) - Check if value is NaN
  • IsInf(from, sign) - Check if value is infinite
  • IsFinite(from) - Check if value is finite
  • IsZeroTime(from) - Check if time is zero

Best Practices & Notes

⚠️ Common Pitfalls
  1. Overflow Behavior: Numeric conversions clamp to the target type's range instead of erroring:

    val, _ := conv.Int8("200")  // Returns 127 (max int8), not error
    
  2. String Trimming: By default, strings are trimmed before conversion:

    conv.Int("  42  ") // Works and returns 42
    
  3. Nil Handling: By default, nil returns zero value:

    conv.Int(nil) // Returns 0, not error
    
  4. Float to Int: Truncates decimal part without rounding:

    conv.Int(3.99) // Returns 3, not 4
    
💡 Recommendations

Use Must* functions only in safe contexts (initialization, constants)

Use *OrDefault for environment variables and config

Check errors for user input conversions

Create custom converters for domain-specific behavior

Use generics (To[T], Slice[T]) for cleaner code

Use Infer when target type is known at compile time

🔒 Thread Safety

The default converter is safe for concurrent use. Custom converters should not be modified after being shared between goroutines.

// Safe - default converter is read-only
go conv.Int("42")
go conv.String(123)

// Safe - create once, use many times
c := conv.NewConverter().WithStrictMode(true)
go c.Int("42")
go c.Int("100")

// Unsafe - don't modify after sharing
c.WithStrictMode(false) // ❌ Race condition if used concurrently
⚡ Performance Tips
  • Use type assertions when source type is known at compile time
  • Reuse converters instead of creating new ones
  • Use Must* variants to eliminate error checks when safe
  • Prefer specific functions (Int, String) over generic To[T] in hot paths
🔧 Customization

Disable automatic trimming and nil handling for stricter behavior:

strict := conv.NewConverter().
    DisableTrimStrings().
    DisableNilAsZero().
    DisableEmptyAsZero()

// Now fails on edge cases
_, err := strict.Int("  42  ")  // Error: whitespace
_, err = strict.Int(nil)        // Error: nil not allowed
_, err = strict.Int("")         // Error: empty string

Error Handling

All conversion errors implement the ConvError type:

val, err := conv.Int("invalid")
if err != nil {
    if conv.IsConvError(err) {
        // Handle conversion-specific error
        if convErr, ok := conv.AsConvError(err); ok {
            fmt.Printf("Failed to convert %v to %s\n", 
                convErr.From, convErr.To)
        }
    }
}

Contributing

Contributions are welcome! Please see the main replify repository for contribution guidelines.

License

This library is part of the replify project.

Documentation

Overview

Package conv provides flexible, panic-free conversion between Go's core scalar types and a handful of stdlib time types.

The package is built around the Converter type, which encapsulates conversion logic and is safe for concurrent use. A shared package-level Converter backs a set of top-level convenience functions so that callers need not manage a Converter instance directly:

n, err := conv.Int("42")          // string  → int
f, err := conv.Float64("3.14")    // string  → float64
b, err := conv.Bool("yes")        // string  → bool
t, err := conv.Time("2024-01-02") // string  → time.Time

Generic Conversion

To[T] is a generic convenience wrapper introduced in Go 1.18 that infers the conversion target from the declared type variable:

val, err := conv.To[int64]("9000000000")

Infer accepts a pointer to the destination variable and assigns the converted value directly, making it ideal for configuration unmarshalling:

var timeout time.Duration
err := conv.Infer(&timeout, "30s")

Must Variants

MustBool, MustInt, MustString, and other Must-prefixed functions mirror their error-returning counterparts but panic on failure. They are intended for use in initialisation code where a conversion failure is a programming error rather than a runtime condition.

Supported Types

bool, string, int / int8 / int16 / int32 / int64, uint / uint8 / uint16 / uint32 / uint64, float32 / float64, time.Time, and time.Duration.

Conversion between any pair of supported types is handled automatically, including numeric widening and narrowing, string-to-number parsing, and several flexible time-layout heuristics. When a conversion cannot be performed, the error value carries a descriptive message that identifies both the source value and the target type.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(from any) (bool, error)

Bool will convert the given value to a bool, returns the default value of false if a conversion cannot be made.

Supported string values for true: "1", "t", "T", "true", "True", "TRUE", "y", "Y", "yes", "Yes", "YES"

Supported string values for false: "0", "f", "F", "false", "False", "FALSE", "n", "N", "no", "No", "NO"

Example:

val, err := conv.Bool("true")
// val -> true
val2, err := conv.Bool(0)
// val2 -> false

Parameters:

  • from: The source value to convert.

Returns:

  • The converted bool value.

func BoolMap

func BoolMap(from any) (map[string]bool, error)

BoolMap converts the given value to map[string]bool.

Parameters:

  • from: The value to convert.

Returns:

  • A map[string]bool.
  • An error if conversion fails.

func BoolOrDefault

func BoolOrDefault(from any, defaultValue bool) bool

BoolOrDefault returns the converted bool value or the provided default if conversion fails.

Example:

val := conv.BoolOrDefault("invalid", true)
// val -> true

Parameters:

  • from: The source value to convert.
  • defaultValue: The value to return if conversion fails.

Returns:

  • The converted bool value, or defaultValue if conversion fails.

func BoolSlice

func BoolSlice(from any) ([]bool, error)

BoolSlice converts the given value to a slice of bool.

Parameters:

  • from: The value to convert (slice, array, or single value).

Returns:

  • A slice of bool.
  • An error if conversion fails.

func Clone

func Clone[T any](v T) (T, error)

Clone creates a deep copy of the given value using JSON serialization and deserialization.

Parameters:

  • `v`: The value to be cloned.

Returns:

  • A deep copy of the input value.

Example:

original := MyStruct{Field: "value"}
clone, err := conv.Clone(original)
if err != nil {
// handle error
}

func Days

func Days(n float64) time.Duration

Days creates a Duration representing the given number of days.

Parameters:

  • n: The number of days.

Returns:

  • A time.Duration representing the specified number of days.

func Duration

func Duration(from any) (time.Duration, error)

Duration will convert the given value to a time.Duration, returns the default value of 0 if a conversion cannot be made.

Example:

val, err := conv.Duration("2h45m")
// val -> 2h45m0s

Parameters:

  • from: The source value to convert.

Returns:

  • The converted time.Duration value.

func DurationOrDefault

func DurationOrDefault(from any, defaultValue time.Duration) time.Duration

DurationOrDefault returns the converted duration or the provided default if conversion fails.

Example:

val := conv.DurationOrDefault("invalid", 30*time.Minute)
// val -> 30m0s

Parameters:

  • from: The source value to convert.
  • defaultValue: The value to return if conversion fails.

Returns:

  • The converted time.Duration value, or defaultValue if conversion fails.

func Float32

func Float32(from any) (float32, error)

Float32 will convert the given value to a float32, returns the default value of 0.0 if a conversion cannot be made.

Example:

val, err := conv.Float32("3.14")
// val -> 3.14

Parameters:

  • from: The source value to convert.

Returns:

  • The converted float32 value.
  • An error if conversion fails.

func Float32OrDefault

func Float32OrDefault(from any, defaultValue float32) float32

Float32OrDefault returns the converted float32 or the provided default if conversion fails.

Parameters:

  • from: The value to convert.
  • defaultValue: The default value to return if conversion fails.

Returns:

  • The converted float32 value or the default value.

func Float64

func Float64(from any) (float64, error)

Float64 will convert the given value to a float64, returns the default value of 0.0 if a conversion cannot be made.

Example:

val, err := conv.Float64("2.71828")
// val -> 2.71828

Parameters:

  • from: The source value to convert.

Returns:

  • The converted float64 value.
  • An error if conversion fails.

func Float64Map

func Float64Map(from any) (map[string]float64, error)

Float64Map converts the given value to map[string]float64.

Parameters:

  • from: The value to convert.

Returns:

  • A map[string]float64.
  • An error if conversion fails.

func Float64OrDefault

func Float64OrDefault(from any, defaultValue float64) float64

Float64OrDefault returns the converted float64 or the provided default if conversion fails.

Example:

val := conv.Float64OrDefault("invalid", 1.61803)
// val -> 1.61803

Parameters:

  • from: The source value to convert.
  • defaultValue: The value to return if conversion fails.

Returns:

  • The converted float64 value, or defaultValue if conversion fails.

func Float64Slice

func Float64Slice(from any) ([]float64, error)

Float64Slice converts the given value to a slice of float64.

Parameters:

  • from: The value to convert (slice, array, or single value).

Returns:

  • A slice of float64.
  • An error if conversion fails.

func Hours

func Hours(n float64) time.Duration

Hours creates a Duration representing the given number of hours.

Parameters:

  • n: The number of hours.

Returns:

  • A time.Duration representing the specified number of hours.

func Infer

func Infer(into, from any) error

Infer will perform conversion by inferring the conversion operation from the base type of a pointer to a supported type. The value is assigned directly so only an error is returned.

Example:

var into int64
err := conv.Infer(&into, "42")
// into -> 42

Parameters:

  • into: A pointer to the variable where the converted value will be stored.
  • from: The source value to convert.

Returns:

  • An error if the conversion fails.

func InferOrDefault

func InferOrDefault[T any](from any, defaultValue T) T

InferOrDefault attempts to infer conversion, using default value on failure.

Example:

val := conv.InferOrDefault[int]("not an int", 100)
// val -> 100
val2 := conv.InferOrDefault[int]("42", 100)
// val2 -> 42

Parameters:

  • from: The source value to convert.
  • defaultValue: The default value to return if conversion fails.

Returns:

  • The converted value or the default value if conversion fails.

func Int

func Int(from any) (int, error)

Int will convert the given value to an int, returns the default value of 0 if a conversion cannot be made.

Example:

val, err := conv.Int("123")
// val -> 123

Parameters:

  • from: The source value to convert.

Returns:

  • The converted int value.
  • An error if conversion fails.

func Int8

func Int8(from any) (int8, error)

Int8 will convert the given value to an int8, returns the default value of 0 if a conversion cannot be made.

Example:

val, err := conv.Int8("127")
// val -> 127

Parameters:

  • from: The source value to convert.

Returns:

  • The converted int8 value.
  • An error if conversion fails.

func Int8OrDefault

func Int8OrDefault(from any, defaultValue int8) int8

Int8OrDefault returns the converted int8 or the provided default if conversion fails.

Example:

val := conv.Int8OrDefault("invalid", 42)
// val -> 42

Parameters:

  • from: The source value to convert.
  • defaultValue: The value to return if conversion fails.

Returns:

  • The converted int8 value, or defaultValue if conversion fails.

func Int16

func Int16(from any) (int16, error)

Int16 will convert the given value to an int16, returns the default value of 0 if a conversion cannot be made.

Example:

val, err := conv.Int16("32000")
// val -> 32000

Parameters:

  • from: The source value to convert.

Returns:

  • The converted int16 value.
  • An error if conversion fails.

func Int16OrDefault

func Int16OrDefault(from any, defaultValue int16) int16

Int16OrDefault returns the converted int16 or the provided default if conversion fails.

Example:

val := conv.Int16OrDefault("invalid", 42)
// val -> 42

Parameters:

  • from: The source value to convert.
  • defaultValue: The value to return if conversion fails.

Returns:

  • The converted int16 value, or defaultValue if conversion fails.

func Int32

func Int32(from any) (int32, error)

Int32 will convert the given value to an int32, returns the default value of 0 if a conversion cannot be made.

Example:

val, err := conv.Int32("2000000000")
// val -> 2000000000

Parameters:

  • from: The source value to convert.

Returns:

  • The converted int32 value.
  • An error if conversion fails.

func Int32OrDefault

func Int32OrDefault(from any, defaultValue int32) int32

Int32OrDefault returns the converted int32 or the provided default if conversion fails.

Example:

val := conv.Int32OrDefault("invalid", 42)
// val -> 42

Parameters:

  • from: The source value to convert.
  • defaultValue: The value to return if conversion fails.

Returns:

  • The converted int32 value, or defaultValue if conversion fails.

func Int64

func Int64(from any) (int64, error)

Int64 will convert the given value to an int64, returns the default value of 0 if a conversion cannot be made.

Example:

val, err := conv.Int64("9000000000")
// val -> 9000000000

Parameters:

  • from: The source value to convert.

Returns:

  • The converted int64 value.
  • An error if conversion fails.

func Int64OrDefault

func Int64OrDefault(from any, defaultValue int64) int64

Int64OrDefault returns the converted int64 or the provided default if conversion fails.

Example:

val := conv.Int64OrDefault("invalid", 1234567890)
// val -> 1234567890

Parameters:

  • from: The source value to convert.
  • defaultValue: The value to return if conversion fails.

Returns:

  • The converted int64 value, or defaultValue if conversion fails.

func Int64Slice

func Int64Slice(from any) ([]int64, error)

Int64Slice converts the given value to a slice of int64.

Parameters:

  • from: The value to convert (slice, array, or single value).

Returns:

  • A slice of int64.
  • An error if conversion fails.

func IntMap

func IntMap(from any) (map[string]int, error)

IntMap converts the given value to map[string]int.

Parameters:

  • from: The value to convert.

Returns:

  • A map[string]int.
  • An error if conversion fails.

func IntOrDefault

func IntOrDefault(from any, defaultValue int) int

IntOrDefault returns the converted int or the provided default if conversion fails.

Example:

val := conv.IntOrDefault("invalid", 42)
// val -> 42

Parameters:

  • from: The source value to convert.
  • defaultValue: The value to return if conversion fails.

Returns:

  • The converted int value, or defaultValue if conversion fails.

func IntSlice

func IntSlice(from any) ([]int, error)

IntSlice converts the given value to a slice of int.

Parameters:

  • from: The value to convert (slice, array, or single value).

Returns:

  • A slice of int.
  • An error if conversion fails.

func IsConvError

func IsConvError(err error) bool

IsConvError checks if the given error is of type ConvError.

Parameters:

  • `err`: The error to be checked.

Returns:

  • A boolean indicating whether the error is a ConvError.

func IsFinite

func IsFinite(from any) bool

IsFinite checks if the given value converts to a finite number. That is, it is neither NaN nor infinite.

Parameters:

  • from: The value to check.

Returns:

  • A boolean indicating whether the converted value is finite (not NaN or infinite).

Example:

  • IsFinite(value) returns true if value is a finite number.

func IsInf

func IsInf(from any, sign int) bool

IsInf checks if the given value converts to infinity. sign > 0 checks for positive infinity, sign < 0 for negative infinity, sign == 0 checks for either.

Parameters:

  • from: The value to check.
  • sign: The sign of infinity to check for.

Returns:

  • A boolean indicating whether the converted value is infinite with the specified sign.

Example:

  • IsInf(value, 1) checks for positive infinity.
  • IsInf(value, -1) checks for negative infinity.
  • IsInf(value, 0) checks for either positive or negative infinity.

func IsNaN

func IsNaN(from any) bool

IsNaN checks if the given value converts to NaN which indicates "Not a Number".

Parameters:

  • from: The value to check.

Returns:

  • A boolean indicating whether the converted value is NaN.

func IsZeroTime

func IsZeroTime(from any) bool

IsZeroTime checks if the given value converts to a zero time.Time.

Parameters:

  • from: The value to check.

Returns:

  • true if the converted time.Time is zero, false otherwise.

func Join

func Join(from any, sep string) (string, error)

Join converts a slice of any type to a single string joined by the specified separator.

Parameters:

  • from: The input value to be converted to a joined string.
  • sep: The separator string to use between elements.

Returns:

  • A single string with all elements joined by the separator.
  • An error if any conversion fails.

func MapTo

func MapTo(from any) (map[string]any, error)

MapTo converts the given value to map[string]any.

Parameters:

  • from: The value to convert.

Returns:

  • A map[string]any.
  • An error if conversion fails.

func Minutes

func Minutes(n float64) time.Duration

Minutes creates a Duration representing the given number of minutes.

Parameters:

  • n: The number of minutes.

Returns:

  • A time.Duration representing the specified number of minutes.

func MustBool

func MustBool(from any) bool

MustBool returns the converted bool value or panics if conversion fails.

Example:

val := conv.MustBool("true")
// val -> true

Parameters:

  • from: The source value to convert.

Returns:

  • The converted bool value.

func MustClone

func MustClone[T any](v T) T

MustClone creates a deep copy of the given value using JSON serialization and deserialization, panicking on failure.

Parameters:

  • `v`: The value to be cloned.

Returns:

  • A deep copy of the input value.

Example:

original := MyStruct{Field: "value"}
clone := conv.MustClone(original)
// use clone

func MustDuration

func MustDuration(from any) time.Duration

MustDuration returns the converted duration or panics if conversion fails.

Example:

val := conv.MustDuration("1h15m")
// val -> 1h15m0s

Parameters:

  • from: The source value to convert.

Returns:

  • The converted time.Duration value.

func MustFloat32

func MustFloat32(from any) float32

MustFloat32 returns the converted float32 or panics if conversion fails.

Parameters:

  • from: The value to convert.

Returns:

  • The converted float32 value.

func MustFloat64

func MustFloat64(from any) float64

MustFloat64 returns the converted float64 or panics if conversion fails.

Parameters:

  • from: The value to convert.

Returns:

  • The converted float64 value.

func MustInfer

func MustInfer[T any](from any) T

MustInfer performs type inference and conversion, panicking on failure.

Example:

val := conv.MustInfer[int]("42")
// val -> 42

Parameters:

  • from: The source value to convert.

Returns:

  • The converted value.

func MustInt

func MustInt(from any) int

MustInt returns the converted int or panics if conversion fails.

Example:

val := conv.MustInt("456")
// val -> 456

Parameters:

  • from: The source value to convert.

Returns:

  • The converted int value.

func MustParseJSON

func MustParseJSON[T any](jsonStr string) T

MustParseJSON is a package-level helper that parses a JSON string into a variable of type T.

Parameters:

  • `jsonStr`: The JSON string to be parsed.

Returns:

  • A variable of type T populated with the parsed data.
  • Panics if the parsing fails.

func MustParseJSONBytes

func MustParseJSONBytes[T any](data []byte) T

MustParseJSONBytes is a package-level helper that parses a JSON byte slice into a variable of type T.

Parameters:

  • `data`: The JSON byte slice to be parsed.

Returns:

  • A variable of type T populated with the parsed data.
  • Panics if the parsing fails.

func MustString

func MustString(from any) string

MustString returns the converted string or panics if conversion fails.

Example:

val := conv.MustString(1001)
// val -> "1001"

Parameters:

  • from: The source value to convert.

Returns:

  • The converted string value.

func MustTime

func MustTime(from any) time.Time

MustTime returns the converted time or panics if conversion fails.

Example:

val := conv.MustTime("2024-12-25T10:00:00Z")
// val -> 2024-12-25 10:00:00 +0000 UTC

Parameters:

  • from: The source value to convert.

Returns:

  • The converted time.Time value.

func MustTo

func MustTo[T any](from any) T

MustTo converts the given value to type T, panicking if conversion fails.

Example:

val := conv.MustTo[int]("42")
// val -> 42

Parameters:

  • from: The source value to convert.

Returns:

  • The converted value of type T.

func MustUint

func MustUint(from any) uint

MustUint returns the converted uint or panics if conversion fails.

Parameters:

  • from: The value to convert.

Returns:

  • The converted uint value.

func ParseJSON

func ParseJSON[T any](jsonStr string) (T, error)

ParseJSON is a package-level helper that parses a JSON string into a variable of type T.

Parameters:

  • `jsonStr`: The JSON string to be parsed.

Returns:

  • A variable of type T populated with the parsed data.
  • An error if the parsing fails.

Example:

var myData MyStruct
myData, err := conv.ParseJSON[MyStruct](jsonString)
if err != nil {
    // handle error
}

func ParseJSONBytes

func ParseJSONBytes[T any](data []byte) (T, error)

ParseJSONBytes is a package-level helper that parses a JSON byte slice into a variable of type T.

Parameters:

  • `data`: The JSON byte slice to be parsed.

Returns:

  • A variable of type T populated with the parsed data.
  • An error if the parsing fails.

Example:

var myData MyStruct
myData, err := conv.ParseJSONBytes[MyStruct](jsonBytes)
if err != nil {
    // handle error
}

func Quote

func Quote(from any) string

Quote returns a double-quoted string safely escaped with Go syntax.

Parameters:

  • from: The value to convert.

Returns:

  • The quoted string value.

func Seconds

func Seconds(n float64) time.Duration

Seconds creates a Duration representing the given number of seconds.

Parameters:

  • n: The number of seconds.

Returns:

  • A time.Duration representing the specified number of seconds.

func Slice

func Slice[T any](from any) ([]T, error)

Slice converts the given value to a slice of type T.

Parameters:

  • from: The value to convert (slice, array, or single value).

Returns:

  • A slice of type T.
  • An error if conversion fails.

Example:

val, err := conv.Slice[int]([]any{"1", 2, 3.0})
//	val -> []int{1, 2, 3}

func SliceOrDefault

func SliceOrDefault[T any](from any, defaultValue []T) []T

SliceOrDefault converts to slice of T, returning default on failure.

Parameters:

  • from: The value to convert (slice, array, or single value).
  • defaultValue: The default slice to return if conversion fails.

Returns:

  • A slice of type T or the default slice if conversion fails.

Example:

val := conv.SliceOrDefault[int]("not a slice", []int{10, 20, 30})
//	val -> []int{10, 20, 30}

func String

func String(from any) (string, error)

String will convert the given value to a string, returns the default value of "" if a conversion cannot be made.

Example:

val, err := conv.String(12345)
// val -> "12345"

Parameters:

  • from: The source value to convert.

Returns:

  • The converted string value.
  • An error if conversion fails.

func StringMap

func StringMap(from any) (map[string]string, error)

StringMap converts the given value to map[string]string.

Parameters:

  • from: The value to convert.

Returns:

  • A map[string]string.
  • An error if conversion fails.

func StringOrDefault

func StringOrDefault(from any, defaultValue string) string

StringOrDefault returns the converted string or the provided default if conversion fails.

Example:

val := conv.StringOrDefault(3.14159, "default")
// val -> "3.14159"

Parameters:

  • from: The source value to convert.
  • defaultValue: The value to return if conversion fails.

Returns:

  • The converted string value, or defaultValue if conversion fails.

func StringOrEmpty

func StringOrEmpty(from any) string

StringOrEmpty returns the converted string or empty string if conversion fails.

Parameters:

  • from: The value to convert.

Returns:

  • The converted string value, or empty string if conversion fails.

func StringSlice

func StringSlice(from any) ([]string, error)

StringSlice converts a slice of any type to a slice of strings.

Parameters:

  • from: The input value to be converted to a slice of strings.

Returns:

  • A slice of strings representing the converted values.
  • An error if any conversion fails.

func Time

func Time(from any) (time.Time, error)

Time will convert the given value to a time.Time, returns the empty struct time.Time{} if a conversion cannot be made.

Example:

val, err := conv.Time("2024-01-02T15:04:05Z")
// val -> 2024-01-02 15:04:05 +0000 UTC

Parameters:

  • from: The source value to convert.

Returns:

  • The converted time.Time value.
  • An error if conversion fails.

func TimeOrDefault

func TimeOrDefault(from any, defaultValue time.Time) time.Time

TimeOrDefault returns the converted time or the provided default if conversion fails.

Example:

val := conv.TimeOrDefault("invalid", time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC))
// val -> 2024-01-01 00:00:00 +0000 UTC

Parameters:

  • from: The source value to convert.
  • defaultValue: The value to return if conversion fails.

Returns:

  • The converted time.Time value, or defaultValue if conversion fails.

func To

func To[T any](from any) (T, error)

To converts the given value to the specified type T. Returns the zero value of T and an error if conversion fails.

Example:

val, err := conv.To[int]("42")
// val -> 42

Parameters:

  • from: The source value to convert.

Returns:

  • The converted value of type T.
  • An error if conversion fails.

func ToOrDefault

func ToOrDefault[T any](from any, defaultValue T) T

ToOrDefault converts the given value to type T, returning defaultValue if conversion fails.

Example:

val := conv.ToOrDefault[int]("invalid", 100)
// val -> 100

Parameters:

  • from: The source value to convert.
  • defaultValue: The value to return if conversion fails.

Returns:

  • The converted value of type T, or defaultValue if conversion fails.

func TrimSpace

func TrimSpace(from any) string

TrimSpace returns the string with all leading and trailing white space removed.

Parameters:

  • from: The value to convert.

Returns:

  • The trimmed string value.

func TryInfer

func TryInfer[T any](from any) (T, bool)

TryInfer attempts to infer conversion, returning success status.

Example:

val, ok := conv.TryInfer[int]("42")
// // val -> 42, ok -> true
val2, ok2 := conv.TryInfer[int]("not an int")
// // val2 -> 0, ok2 -> false

Parameters:

  • from: The source value to convert.

Returns:

  • The converted value.

func Uint

func Uint(from any) (uint, error)

Uint will convert the given value to a uint, returns the default value of 0 if a conversion cannot be made.

Example:

val, err := conv.Uint("12345")
// val -> 12345

Parameters:

  • from: The source value to convert.

Returns:

  • The converted uint value.
  • An error if conversion fails.

func Uint8

func Uint8(from any) (uint8, error)

Uint8 will convert the given value to a uint8, returns the default value of 0 if a conversion cannot be made.

Example:

val, err := conv.Uint8("255")
// val -> 255

Parameters:

  • from: The source value to convert.

Returns:

  • The converted uint8 value.
  • An error if conversion fails.

func Uint8OrDefault

func Uint8OrDefault(from any, defaultValue uint8) uint8

Uint8OrDefault returns the converted uint8 or the provided default if conversion fails.

Parameters:

  • from: The value to convert.
  • defaultValue: The default value to return if conversion fails.

Returns:

  • The converted uint8 value or the default value.

func Uint16

func Uint16(from any) (uint16, error)

Uint16 will convert the given value to a uint16, returns the default value of 0 if a conversion cannot be made.

Example:

val, err := conv.Uint16("65000")
// val -> 65000

Parameters:

  • from: The source value to convert.

Returns:

  • The converted uint16 value.
  • An error if conversion fails.

func Uint16OrDefault

func Uint16OrDefault(from any, defaultValue uint16) uint16

Uint16OrDefault returns the converted uint16 or the provided default if conversion fails.

Parameters:

  • from: The value to convert.
  • defaultValue: The default value to return if conversion fails.

Returns:

  • The converted uint16 value or the default value.

func Uint32

func Uint32(from any) (uint32, error)

Uint32 will convert the given value to a uint32, returns the default value of 0 if a conversion cannot be made.

Example:

val, err := conv.Uint32("4000000000")
// val -> 4000000000

Parameters:

  • from: The source value to convert.

Returns:

  • The converted uint32 value.
  • An error if conversion fails.

func Uint32OrDefault

func Uint32OrDefault(from any, defaultValue uint32) uint32

Uint32OrDefault returns the converted uint32 or the provided default if conversion fails.

Parameters:

  • from: The value to convert.
  • defaultValue: The default value to return if conversion fails.

Returns:

  • The converted uint32 value or the default value.

func Uint64

func Uint64(from any) (uint64, error)

Uint64 will convert the given value to a uint64, returns the default value of 0 if a conversion cannot be made.

Example:

val, err := conv.Uint64("9000000000")
// val -> 9000000000

Parameters:

  • from: The source value to convert.

Returns:

  • The converted uint64 value.
  • An error if conversion fails.

func Uint64OrDefault

func Uint64OrDefault(from any, defaultValue uint64) uint64

Uint64OrDefault returns the converted uint64 or the provided default if conversion fails.

Example:

val := conv.Uint64OrDefault("invalid", 9876543210)
// val -> 9876543210

Parameters:

  • from: The source value to convert.
  • defaultValue: The value to return if conversion fails.

Returns:

  • The converted uint64 value, or defaultValue if conversion fails.

func UintOrDefault

func UintOrDefault(from any, defaultValue uint) uint

UintOrDefault returns the converted uint or the provided default if conversion fails.

Parameters:

  • from: The value to convert.
  • defaultValue: The default value to return if conversion fails.

Returns:

  • The converted uint value or the default value.

Types

type ConvError

type ConvError struct {
	From    any    // The source value
	To      string // The target type name
	Message string // Additional error message
}

ConvError represents a type-conversion failure and its diagnostic context. It includes the source value, the target type name, and an optional custom message.

func AsConvError

func AsConvError(err error) (*ConvError, bool)

AsConvError attempts to cast the given error to a ConvError.

Parameters:

  • `err`: The error to be cast.

Returns:

  • A pointer to the ConvError if the cast is successful.

func (*ConvError) Error

func (e *ConvError) Error() string

Error implements the error interface for ConvError.

It returns the custom message if provided; otherwise, it constructs a default error message indicating the source value and target type.

Returns:

  • A string representing the error message.

type Converter

type Converter struct {
	// contains filtered or unexported fields
}

Converter implements type conversions with configurable options. It is safe for concurrent use by multiple goroutines.

func NewConverter

func NewConverter() *Converter

NewConverter creates a new Converter instance with default settings.

Returns:

  • A pointer to a newly created Converter instance.

func (*Converter) Bool

func (c *Converter) Bool(from any) (bool, error)

Bool attempts to convert the given value to bool, returns the zero value and an error on failure.

Supported conversions:

  • string: "1", "t", "T", "true", "True", "TRUE", "y", "Y", "yes", "Yes", "YES" → true
  • string: "0", "f", "F", "false", "False", "FALSE", "n", "N", "no", "No", "NO" → false
  • numeric: non-zero → true, zero → false
  • bool: returned as-is
  • slice/map/array: len > 0 → true, empty → false
  • time.Time: non-zero → true, zero → false

Parameters:

  • from: The value to convert.

Returns:

  • The converted bool value.
  • An error if conversion fails.

func (*Converter) Clone

func (c *Converter) Clone() *Converter

Clone creates a deep copy of the Converter instance.

Returns:

  • A pointer to the cloned Converter instance.

func (*Converter) DateFormats

func (c *Converter) DateFormats() []string

DateFormats returns the configured date formats.

Returns:

  • A slice of strings representing the date formats.

func (*Converter) DisableEmptyAsZero

func (c *Converter) DisableEmptyAsZero() *Converter

DisableEmptyAsZero disables returning zero value for empty string inputs.

Returns:

  • A pointer to the modified Converter instance (enabling method chaining).

func (*Converter) DisableNilAsZero

func (c *Converter) DisableNilAsZero() *Converter

DisableNilAsZero disables returning zero value for nil inputs.

Returns:

  • A pointer to the modified Converter instance (enabling method chaining).

func (*Converter) DisableTrimStrings

func (c *Converter) DisableTrimStrings() *Converter

DisableTrimStrings disables string trimming before conversion.

Returns:

  • A pointer to the modified Converter instance (enabling method chaining).

func (*Converter) Duration

func (c *Converter) Duration(from any) (time.Duration, error)

Duration attempts to convert the given value to time.Duration, returns the zero value and an error on failure.

String parsing supports Go duration format (e.g., "1h30m") and numeric strings. Numeric values are treated as nanoseconds. Float values are treated as seconds (e.g., 1.5 = 1.5 seconds).

Parameters:

  • from: The value to convert.

Returns:

  • The converted time.Duration value.
  • An error if conversion fails.

func (*Converter) EnableEmptyAsZero

func (c *Converter) EnableEmptyAsZero() *Converter

EnableEmptyAsZero enables returning zero value for empty string inputs.

Returns:

  • A pointer to the modified Converter instance (enabling method chaining).

func (*Converter) EnableNilAsZero

func (c *Converter) EnableNilAsZero() *Converter

EnableNilAsZero enables returning zero value for nil inputs.

Returns:

  • A pointer to the modified Converter instance (enabling method chaining).

func (*Converter) EnableTrimStrings

func (c *Converter) EnableTrimStrings() *Converter

EnableTrimStrings enables string trimming before conversion.

Returns:

  • A pointer to the modified Converter instance (enabling method chaining).

func (*Converter) Float32

func (c *Converter) Float32(from any) (float32, error)

Float32 attempts to convert the given value to float32, returns the zero value and an error on failure.

Note: Values exceeding float32 range are clamped to max/min float32.

Parameters:

  • from: The value to convert.

Returns:

  • The converted float32 value.
  • An error if conversion fails.

func (*Converter) Float64

func (c *Converter) Float64(from any) (float64, error)

Float64 attempts to convert the given value to float64, returns the zero value and an error on failure.

Parameters:

  • from: The value to convert.

Returns:

  • The converted float64 value.
  • An error if conversion fails.

func (*Converter) FromJSON

func (c *Converter) FromJSON(jsonStr string, into any) error

FromJSON parses a JSON string and populates the provided variable with the resulting data structure.

Parameters:

  • `jsonStr`: The JSON string to be parsed.
  • `into`: A pointer to the variable where the parsed data will be stored.

Returns:

  • An error if the parsing fails or if the input JSON string is empty (unless `emptyAsZero` is set).

Example:

var myData MyStruct
err := conv.FromJSON(jsonString, &myData)
if err != nil {
    // handle error
}

func (*Converter) FromJSONBytes

func (c *Converter) FromJSONBytes(data []byte, into any) error

FromJSONBytes parses a JSON byte slice and populates the provided variable with the resulting data structure.

Parameters:

  • `data`: The JSON byte slice to be parsed.
  • `into`: A pointer to the variable where the parsed data will be stored.

Returns:

  • An error if the parsing fails or if the input byte slice is empty (unless `emptyAsZero` is set).

Example:

var myData MyStruct
err := conv.FromJSONBytes(jsonBytes, &myData)
if err != nil {
    // handle error
}

func (*Converter) FromJSONReader

func (c *Converter) FromJSONReader(r io.Reader, into any) error

FromJSONReader parses JSON data from an io.Reader and populates the provided variable with the resulting data structure.

Parameters:

  • `r`: An io.Reader from which to read the JSON data.
  • `into`: A pointer to the variable where the parsed data will be stored.

Returns:

  • An error if the parsing fails.

Example:

var myData MyStruct
reader := strings.NewReader(jsonString) // or use file reader, network reader, etc.
file, err := os.Open("data.json") // use file reader
err := conv.FromJSONReader(reader, &myData)
if err != nil {
	   // handle error
}

func (*Converter) Infer

func (c *Converter) Infer(into, from any) error

Infer will perform conversion by inferring the conversion operation from the base type of a pointer to a supported type. The value is assigned directly so only an error is returned.

Example:

var into int64
err := conv.Infer(&into, "42")
// into -> 42

var t time.Time
err := conv.Infer(&t, "2024-01-15")
// t -> 2024-01-15 00:00:00 +0000 UTC

Parameters:

  • into: A pointer to the target variable.
  • from: The source value to convert.

Returns:

  • An error if the conversion fails or if `into` is not a settable pointer.

func (*Converter) Int

func (c *Converter) Int(from any) (int, error)

Int attempts to convert the given value to int, returns the zero value and an error on failure.

Parameters:

  • from: The value to convert.

Returns:

  • The converted int value.
  • An error if conversion fails.

func (*Converter) Int8

func (c *Converter) Int8(from any) (int8, error)

Int8 attempts to convert the given value to int8, returns the zero value and an error on failure.

Parameters:

  • from: The value to convert.

Returns:

  • The converted int8 value.
  • An error if conversion fails.

func (*Converter) Int16

func (c *Converter) Int16(from any) (int16, error)

Int16 attempts to convert the given value to int16, returns the zero value and an error on failure.

Parameters:

  • from: The value to convert.

Returns:

  • The converted int16 value.
  • An error if conversion fails.

func (*Converter) Int32

func (c *Converter) Int32(from any) (int32, error)

Int32 attempts to convert the given value to int32, returns the zero value and an error on failure.

Parameters:

  • from: The value to convert.

Returns:

  • The converted int32 value.
  • An error if conversion fails.

func (*Converter) Int64

func (c *Converter) Int64(from any) (int64, error)

Int64 attempts to convert the given value to int64, returns the zero value and an error on failure.

Parameters:

  • from: The value to convert.

Returns:

  • The converted int64 value.
  • An error if conversion fails.

func (*Converter) IsStrictMode

func (c *Converter) IsStrictMode() bool

IsStrictMode returns whether strict mode is enabled.

Returns:

  • A boolean indicating if strict mode is enabled.

func (*Converter) Locale

func (c *Converter) Locale() string

Locale returns the configured locale.

Returns:

  • A string representing the locale.

func (*Converter) Reset

func (c *Converter) Reset() *Converter

Reset resets the Converter to its default settings.

Returns:

  • A pointer to the reset Converter instance.

func (*Converter) String

func (c *Converter) String(from any) (string, error)

String returns the string representation from the given interface{} value. This function cannot fail for most types - it will use fmt.Sprintf as fallback.

Parameters:

  • from: The value to convert.

Returns:

  • The converted string value.
  • An error (currently always nil for compatibility, but check it for future-proofing).

func (*Converter) Time

func (c *Converter) Time(from any) (time.Time, error)

Time attempts to convert the given value to time.Time, returns the zero value of time.Time and an error on failure.

String parsing supports multiple date formats. Use WithDateFormats() to customize.

Parameters:

  • from: The value to convert.

Returns:

  • The converted time.Time value.
  • An error if conversion fails.

func (*Converter) ToBoolMap

func (c *Converter) ToBoolMap(from any) (map[string]bool, error)

ToBoolMap converts the given value to a map[string]bool.

Parameters:

  • from: The value to convert.

Returns:

  • A map[string]bool.
  • An error if conversion fails.

func (*Converter) ToBoolSlice

func (c *Converter) ToBoolSlice(from any) ([]bool, error)

ToBoolSlice converts the given value to a slice of bool.

Parameters:

  • from: The value to convert (slice, array, or single value).

Returns:

  • A slice of bool.
  • An error if conversion fails.

func (*Converter) ToFloat64Map

func (c *Converter) ToFloat64Map(from any) (map[string]float64, error)

ToFloat64Map converts the given value to a map[string]float64.

Parameters:

  • from: The value to convert.

Returns:

  • A map[string]float64.
  • An error if conversion fails.

func (*Converter) ToFloat64Slice

func (c *Converter) ToFloat64Slice(from any) ([]float64, error)

ToFloat64Slice converts the given value to a slice of float64.

Parameters:

  • from: The value to convert (slice, array, or single value).

Returns:

  • A slice of float64.
  • An error if conversion fails.

func (*Converter) ToInt64Slice

func (c *Converter) ToInt64Slice(from any) ([]int64, error)

ToInt64Slice converts the given value to a slice of int64.

Parameters:

  • from: The value to convert (slice, array, or single value).

Returns:

  • A slice of int64.
  • An error if conversion fails.

func (*Converter) ToIntMap

func (c *Converter) ToIntMap(from any) (map[string]int, error)

ToIntMap converts the given value to a map[string]int.

Parameters:

  • from: The value to convert.

Returns:

  • A map[string]int.
  • An error if conversion fails.

func (*Converter) ToIntSlice

func (c *Converter) ToIntSlice(from any) ([]int, error)

ToIntSlice converts the given value to a slice of int.

Parameters:

  • from: The value to convert (slice, array, or single value).

Returns:

  • A slice of int.
  • An error if conversion fails.

func (*Converter) ToMap

func (c *Converter) ToMap(from any) (map[string]any, error)

ToMap converts the given value to a map[string]any.

Supported conversions:

  • map[string]any: returned as-is
  • map[K]V: keys converted to string, values to any
  • struct: field names as keys, field values as values

Parameters:

  • from: The value to convert.

Returns:

  • A map[string]any.
  • An error if conversion fails.

func (*Converter) ToSlice

func (c *Converter) ToSlice(from any) ([]any, error)

ToSlice converts the given value to a slice of the specified element type. If the input is not a slice/array, it wraps the value in a single-element slice.

Parameters:

  • from: The value to convert.

Returns:

  • A slice of interface{} containing the converted elements.
  • An error if conversion fails.

func (*Converter) ToStringMap

func (c *Converter) ToStringMap(from any) (map[string]string, error)

ToStringMap converts the given value to a map[string]string.

Parameters:

  • from: The value to convert.

Returns:

  • A map[string]string.
  • An error if conversion fails.

func (*Converter) ToStringSlice

func (c *Converter) ToStringSlice(from any) ([]string, error)

ToStringSlice converts the given value to a slice of string.

Parameters:

  • from: The value to convert (slice, array, or single value).

Returns:

  • A slice of string.
  • An error if conversion fails.

func (*Converter) Uint

func (c *Converter) Uint(from any) (uint, error)

Uint attempts to convert the given value to uint, returns the zero value and an error on failure.

Parameters:

  • from: The value to convert.

Returns:

  • The converted uint value.
  • An error if conversion fails.

func (*Converter) Uint8

func (c *Converter) Uint8(from any) (uint8, error)

Uint8 attempts to convert the given value to uint8, returns the zero value and an error on failure.

Parameters:

  • from: The value to convert.

Returns:

  • The converted uint8 value.
  • An error if conversion fails.

func (*Converter) Uint16

func (c *Converter) Uint16(from any) (uint16, error)

Uint16 attempts to convert the given value to uint16, returns the zero value and an error on failure.

Parameters:

  • from: The value to convert.

Returns:

  • The converted uint16 value.
  • An error if conversion fails.

func (*Converter) Uint32

func (c *Converter) Uint32(from any) (uint32, error)

Uint32 attempts to convert the given value to uint32, returns the zero value and an error on failure.

Parameters:

  • from: The value to convert.

Returns:

  • The converted uint32 value.
  • An error if conversion fails.

func (*Converter) Uint64

func (c *Converter) Uint64(from any) (uint64, error)

Uint64 attempts to convert the given value to uint64, returns the zero value and an error on failure.

Note: Negative values are converted to 0 (underflow protection).

Parameters:

  • from: The value to convert.

Returns:

  • The converted uint64 value.
  • An error if conversion fails.

func (*Converter) WithDateFormats

func (c *Converter) WithDateFormats(formats ...string) *Converter

WithDateFormats sets custom date formats for time parsing. Formats are tried in order when parsing time strings.

Parameters:

  • formats: Variadic list of date format strings.

Returns:

  • A pointer to the modified Converter instance (enabling method chaining).

func (*Converter) WithEmptyAsZero

func (c *Converter) WithEmptyAsZero(v bool) *Converter

WithEmptyAsZero enables or disables returning zero value for empty string inputs.

Parameters:

  • v: Boolean indicating whether empty strings should return zero value.

Returns:

  • A pointer to the modified Converter instance (enabling method chaining).

func (*Converter) WithLocale

func (c *Converter) WithLocale(locale string) *Converter

WithLocale sets the locale for parsing operations.

Parameters:

  • locale: Locale string (e.g., "en_US", "vi_VN").

Returns:

  • A pointer to the modified Converter instance (enabling method chaining).

func (*Converter) WithNilAsZero

func (c *Converter) WithNilAsZero(v bool) *Converter

WithNilAsZero enables or disables returning zero value for nil inputs.

Parameters:

  • v: Boolean indicating whether nil should return zero value.

Returns:

  • A pointer to the modified Converter instance (enabling method chaining).

func (*Converter) WithStrictMode

func (c *Converter) WithStrictMode(v bool) *Converter

WithStrictMode enables or disables strict mode for conversions. In strict mode, lossy conversions (e.g., float to int) return an error.

Parameters:

  • v: Boolean indicating whether strict mode should be enabled.

Returns:

  • A pointer to the modified Converter instance (enabling method chaining).

func (*Converter) WithTrimStrings

func (c *Converter) WithTrimStrings(v bool) *Converter

WithTrimStrings enables or disables string trimming before conversion.

Parameters:

  • v: Boolean indicating whether strings should be trimmed.

Returns:

  • A pointer to the modified Converter instance (enabling method chaining).

Jump to

Keyboard shortcuts

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