cast

repository·master·Indexed 26 days ago

https://github.com/spf13/cast

A Go library for safe type conversion between different Go types, specifically designed for handling dynamic data from interfaces or configuration files such as YAML, TOML, and JSON. It provides two patterns of conversion: To[Type] methods that return zero values on failure, and To[Type]E methods that return both the converted value and an error.

Tokens
3.8K
Snippets
13
Records
35
Agent score
87%

What's inside cast

  1. Convert types using Cast

    master

    Cast provides a library for consistent and safe type conversion in Go, particularly useful when working with interface{} or dynamic data from formats like YAML, TOML, or JSON.

    There are two patterns of conversion methods available:

    1. To[Type] methods: These always return the desired type. If the input cannot be converted, the zero value for that type (e.g., 0, "", or nil) is returned.
    2. To[Type]E methods: These return the converted value and an error. This allows you to distinguish between a successful conversion to a zero value and a failed conversion.
  2. Convert values to integers with ToInt

    master

    Use cast.ToInt(in interface{}) to convert various types to an integer. If the input cannot be converted, it returns 0. Supported conversions include floats (truncated), numeric strings, and booleans (true becomes 1, false becomes 0).

    cast.ToInt(8)                  // 8
    cast.ToInt(8.31)               // 8
    cast.ToInt("8")                // 8
    cast.ToInt(true)                // 1
    cast.ToInt(false)              // 0
    
    var eight interface{} = 8
    cast.ToInt(eight)              // 8
    cast.ToInt(nil)                // 0
  3. Convert values to strings with ToString

    master

    Use cast.ToString(in interface{}) to convert various types to a string. If the input is nil or cannot be converted, it returns an empty string "".

    cast.ToString("mayonegg")         // "mayonegg"
    cast.ToString(8)                  // "8"
    cast.ToString(8.31)               // "8.31"
    cast.ToString([]byte("one time")) // "one time"
    cast.ToString(nil)                // ""
    
    var foo interface{} = "one more time"
    cast.ToString(foo)                // "one more time"
  4. Parse a string into time.Time with a specific location using StringToDateInDefaultLocation

    master
    Use StringToDateInDefaultLocation to parse a string into a time.Time object using predefined formats, while specifying a *time.Location for inputs that do not contain timezone information.
  5. Cast values to specific integer types

    master

    The package provides explicit functions for casting to specific integer types. These functions return the value and an error if the conversion is unsuccessful.

    • ToIntE(i any) (int, error)
    • ToInt8E(i any) (int8, error)
    • ToInt16E(i any) (int16, error)
    • ToInt32E(i any) (int32, error)
    • ToInt64E(i any) (int64, error)
  6. Cast values to basic types with To

    master
    Use To[T](i any) to cast any value to a supported basic type. This function returns the zero value of the target type if the casting fails, as it ignores errors internally. Supported types are defined by the Basic interface: string, bool, Number (int/uint/float variants), time.Time, and time.Duration.
  7. Cast any value to a slice of strings with ToStringSliceE

    master

    Use ToStringSliceE to attempt to cast any value into a []string.

    Supported behaviors:

    • string: Returns a slice of strings split by whitespace (using strings.Fields).
    • any: Attempts to convert the value to a single string using ToStringE and returns it as a single-element slice []string{str}.
    • slice/array: If the input is a slice or array of types that can be converted to strings, it returns a slice of those strings.

    If the conversion fails, it returns an error.

  8. Cast values to basic types

    master
    The cast package provides functions to convert any values into basic Go types. For every conversion function that returns a value (e.g., ToInt), there is a corresponding function ending in E (e.g., ToIntE) that returns both the value and an error. Use the non-E versions if you want a zero-value on failure, and the E versions if you need to handle conversion errors.
  9. Cast values to specific unsigned integer types

    master

    The package provides explicit functions for casting to unsigned integer types. Note that if the input value is negative, these functions will return an error: unable to cast negative value.

    • ToUintE(i any) (uint, error)
    • ToUint8E(i any) (uint8, error)
    • ToUint16E(i any) (uint16, error)
    • ToUint32E(i any) (uint32, error)
    • ToUint64E(i any) (uint64, error)
  10. Cast any value to time.Duration with ToDurationE

    master

    Use ToDurationE to convert an interface value to a time.Duration.

    Supported types:

    • time.Duration: Returns the value directly.
    • Integers/Unsigned Integers: Converted to int64 then to time.Duration.
    • Floats: Converted to float64 then to time.Duration.
    • string: Parsed using time.ParseDuration. If the string does not contain any duration units (n, s, u, m, h), it appends ns to the string before parsing.
    • nil: Returns 0.

    If the input is an alias that can be resolved, it will attempt to resolve it before failing.

  11. Cast any value to time.Time with ToTimeE

    master
    Use ToTimeE to convert an interface value to a time.Time object. It defaults to using the UTC timezone. Supported types include time.Time, string (via predefined formats), json.Number, various integer types (int, int32, int64, uint, etc.), and nil (which returns a zero time.Time).
  12. Cast values with error handling using ToE

    master
    Use ToE[T](i any) when you need to handle potential casting failures. It returns the casted value and an error if the conversion is not possible. This is the safer alternative to To[T] when the input value's type is uncertain.