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 ¶
- func Bool(from any) (bool, error)
- func BoolMap(from any) (map[string]bool, error)
- func BoolOrDefault(from any, defaultValue bool) bool
- func BoolSlice(from any) ([]bool, error)
- func Clone[T any](v T) (T, error)
- func Days(n float64) time.Duration
- func Duration(from any) (time.Duration, error)
- func DurationOrDefault(from any, defaultValue time.Duration) time.Duration
- func Float32(from any) (float32, error)
- func Float32OrDefault(from any, defaultValue float32) float32
- func Float64(from any) (float64, error)
- func Float64Map(from any) (map[string]float64, error)
- func Float64OrDefault(from any, defaultValue float64) float64
- func Float64Slice(from any) ([]float64, error)
- func Hours(n float64) time.Duration
- func Infer(into, from any) error
- func InferOrDefault[T any](from any, defaultValue T) T
- func Int(from any) (int, error)
- func Int8(from any) (int8, error)
- func Int8OrDefault(from any, defaultValue int8) int8
- func Int16(from any) (int16, error)
- func Int16OrDefault(from any, defaultValue int16) int16
- func Int32(from any) (int32, error)
- func Int32OrDefault(from any, defaultValue int32) int32
- func Int64(from any) (int64, error)
- func Int64OrDefault(from any, defaultValue int64) int64
- func Int64Slice(from any) ([]int64, error)
- func IntMap(from any) (map[string]int, error)
- func IntOrDefault(from any, defaultValue int) int
- func IntSlice(from any) ([]int, error)
- func IsConvError(err error) bool
- func IsFinite(from any) bool
- func IsInf(from any, sign int) bool
- func IsNaN(from any) bool
- func IsZeroTime(from any) bool
- func Join(from any, sep string) (string, error)
- func MapTo(from any) (map[string]any, error)
- func Minutes(n float64) time.Duration
- func MustBool(from any) bool
- func MustClone[T any](v T) T
- func MustDuration(from any) time.Duration
- func MustFloat32(from any) float32
- func MustFloat64(from any) float64
- func MustInfer[T any](from any) T
- func MustInt(from any) int
- func MustParseJSON[T any](jsonStr string) T
- func MustParseJSONBytes[T any](data []byte) T
- func MustString(from any) string
- func MustTime(from any) time.Time
- func MustTo[T any](from any) T
- func MustUint(from any) uint
- func ParseJSON[T any](jsonStr string) (T, error)
- func ParseJSONBytes[T any](data []byte) (T, error)
- func Quote(from any) string
- func Seconds(n float64) time.Duration
- func Slice[T any](from any) ([]T, error)
- func SliceOrDefault[T any](from any, defaultValue []T) []T
- func String(from any) (string, error)
- func StringMap(from any) (map[string]string, error)
- func StringOrDefault(from any, defaultValue string) string
- func StringOrEmpty(from any) string
- func StringSlice(from any) ([]string, error)
- func Time(from any) (time.Time, error)
- func TimeOrDefault(from any, defaultValue time.Time) time.Time
- func To[T any](from any) (T, error)
- func ToOrDefault[T any](from any, defaultValue T) T
- func TrimSpace(from any) string
- func TryInfer[T any](from any) (T, bool)
- func Uint(from any) (uint, error)
- func Uint8(from any) (uint8, error)
- func Uint8OrDefault(from any, defaultValue uint8) uint8
- func Uint16(from any) (uint16, error)
- func Uint16OrDefault(from any, defaultValue uint16) uint16
- func Uint32(from any) (uint32, error)
- func Uint32OrDefault(from any, defaultValue uint32) uint32
- func Uint64(from any) (uint64, error)
- func Uint64OrDefault(from any, defaultValue uint64) uint64
- func UintOrDefault(from any, defaultValue uint) uint
- type ConvError
- type Converter
- func (c *Converter) Bool(from any) (bool, error)
- func (c *Converter) Clone() *Converter
- func (c *Converter) DateFormats() []string
- func (c *Converter) DisableEmptyAsZero() *Converter
- func (c *Converter) DisableNilAsZero() *Converter
- func (c *Converter) DisableTrimStrings() *Converter
- func (c *Converter) Duration(from any) (time.Duration, error)
- func (c *Converter) EnableEmptyAsZero() *Converter
- func (c *Converter) EnableNilAsZero() *Converter
- func (c *Converter) EnableTrimStrings() *Converter
- func (c *Converter) Float32(from any) (float32, error)
- func (c *Converter) Float64(from any) (float64, error)
- func (c *Converter) FromJSON(jsonStr string, into any) error
- func (c *Converter) FromJSONBytes(data []byte, into any) error
- func (c *Converter) FromJSONReader(r io.Reader, into any) error
- func (c *Converter) Infer(into, from any) error
- func (c *Converter) Int(from any) (int, error)
- func (c *Converter) Int8(from any) (int8, error)
- func (c *Converter) Int16(from any) (int16, error)
- func (c *Converter) Int32(from any) (int32, error)
- func (c *Converter) Int64(from any) (int64, error)
- func (c *Converter) IsStrictMode() bool
- func (c *Converter) Locale() string
- func (c *Converter) Reset() *Converter
- func (c *Converter) String(from any) (string, error)
- func (c *Converter) Time(from any) (time.Time, error)
- func (c *Converter) ToBoolMap(from any) (map[string]bool, error)
- func (c *Converter) ToBoolSlice(from any) ([]bool, error)
- func (c *Converter) ToFloat64Map(from any) (map[string]float64, error)
- func (c *Converter) ToFloat64Slice(from any) ([]float64, error)
- func (c *Converter) ToInt64Slice(from any) ([]int64, error)
- func (c *Converter) ToIntMap(from any) (map[string]int, error)
- func (c *Converter) ToIntSlice(from any) ([]int, error)
- func (c *Converter) ToMap(from any) (map[string]any, error)
- func (c *Converter) ToSlice(from any) ([]any, error)
- func (c *Converter) ToStringMap(from any) (map[string]string, error)
- func (c *Converter) ToStringSlice(from any) ([]string, error)
- func (c *Converter) Uint(from any) (uint, error)
- func (c *Converter) Uint8(from any) (uint8, error)
- func (c *Converter) Uint16(from any) (uint16, error)
- func (c *Converter) Uint32(from any) (uint32, error)
- func (c *Converter) Uint64(from any) (uint64, error)
- func (c *Converter) WithDateFormats(formats ...string) *Converter
- func (c *Converter) WithEmptyAsZero(v bool) *Converter
- func (c *Converter) WithLocale(locale string) *Converter
- func (c *Converter) WithNilAsZero(v bool) *Converter
- func (c *Converter) WithStrictMode(v bool) *Converter
- func (c *Converter) WithTrimStrings(v bool) *Converter
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Bool ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
MustFloat32 returns the converted float32 or panics if conversion fails.
Parameters:
- from: The value to convert.
Returns:
- The converted float32 value.
func MustFloat64 ¶
MustFloat64 returns the converted float64 or panics if conversion fails.
Parameters:
- from: The value to convert.
Returns:
- The converted float64 value.
func MustInfer ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
MustUint returns the converted uint or panics if conversion fails.
Parameters:
- from: The value to convert.
Returns:
- The converted uint value.
func ParseJSON ¶
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 ¶
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 ¶
Quote returns a double-quoted string safely escaped with Go syntax.
Parameters:
- from: The value to convert.
Returns:
- The quoted string value.
func Seconds ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
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 ¶
Clone creates a deep copy of the Converter instance.
Returns:
- A pointer to the cloned Converter instance.
func (*Converter) DateFormats ¶
DateFormats returns the configured date formats.
Returns:
- A slice of strings representing the date formats.
func (*Converter) DisableEmptyAsZero ¶
DisableEmptyAsZero disables returning zero value for empty string inputs.
Returns:
- A pointer to the modified Converter instance (enabling method chaining).
func (*Converter) DisableNilAsZero ¶
DisableNilAsZero disables returning zero value for nil inputs.
Returns:
- A pointer to the modified Converter instance (enabling method chaining).
func (*Converter) DisableTrimStrings ¶
DisableTrimStrings disables string trimming before conversion.
Returns:
- A pointer to the modified Converter instance (enabling method chaining).
func (*Converter) Duration ¶
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 ¶
EnableEmptyAsZero enables returning zero value for empty string inputs.
Returns:
- A pointer to the modified Converter instance (enabling method chaining).
func (*Converter) EnableNilAsZero ¶
EnableNilAsZero enables returning zero value for nil inputs.
Returns:
- A pointer to the modified Converter instance (enabling method chaining).
func (*Converter) EnableTrimStrings ¶
EnableTrimStrings enables string trimming before conversion.
Returns:
- A pointer to the modified Converter instance (enabling method chaining).
func (*Converter) Float32 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
IsStrictMode returns whether strict mode is enabled.
Returns:
- A boolean indicating if strict mode is enabled.
func (*Converter) Locale ¶
Locale returns the configured locale.
Returns:
- A string representing the locale.
func (*Converter) Reset ¶
Reset resets the Converter to its default settings.
Returns:
- A pointer to the reset Converter instance.
func (*Converter) String ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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).