Skip to main content

cast - Type Casting Library

cast is a simple and easy-to-use type conversion function library that provides conversion from strings to various Go basic types. Minimum supported Go version is 1.21.0.

Installation

go get -u go-slim.dev/cast

Quick Start

package main

import (
"fmt"
"go-slim.dev/cast"
)

func main() {
// String to integer
num, _ := cast.Int("42")
fmt.Println(num) // 42

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

// String to time
t, _ := cast.Time("2023-12-25T10:30:45Z")
fmt.Println(t)
}

Bool - Boolean Conversion

Function Signature

func Bool(s string) (bool, error)

Description

Parses a string into a bool value, using the standard library's strconv.ParseBool internally.

Supported values:

  • true: "1", "t", "T", "true", "TRUE", "True"
  • false: "0", "f", "F", "false", "FALSE", "False"

Examples

// Returns true
cast.Bool("true")
cast.Bool("TRUE")
cast.Bool("1")
cast.Bool("t")

// Returns false
cast.Bool("false")
cast.Bool("FALSE")
cast.Bool("0")
cast.Bool("f")

// Returns error
cast.Bool("yes") // Unsupported value
cast.Bool("no") // Unsupported value

Uint Series - Unsigned Integer Conversion

Function Signatures

func Uint(s string) (uint, error)
func Uint8(s string) (uint8, error)
func Uint16(s string) (uint16, error)
func Uint32(s string) (uint32, error)
func Uint64(s string) (uint64, error)

Description

Parses strings into corresponding unsigned integer types, using the standard library's strconv.ParseUint internally.

Supported formats:

  • Decimal: "123"
  • Hexadecimal: "0x7B" (0x prefix)
  • Octal: "0173" (0 prefix)
  • Binary: "0b1111011" (0b prefix)

Examples

// Decimal
num, _ := cast.Uint("123") // 123
num8, _ := cast.Uint8("255") // 255

// Hexadecimal
num, _ := cast.Uint("0xFF") // 255

// Octal
num, _ := cast.Uint("0777") // 511

// Binary
num, _ := cast.Uint("0b1010") // 10

// Out of range returns error
_, err := cast.Uint8("256") // Error: exceeds uint8 range

Int Series - Signed Integer Conversion

Function Signatures

func Int(s string) (int, error)
func Int8(s string) (int8, error)
func Int16(s string) (int16, error)
func Int32(s string) (int32, error)
func Int64(s string) (int64, error)

Description

Parses strings into corresponding signed integer types, using the standard library's strconv.ParseInt internally.

Supported formats:

  • Decimal: "123", "-123"
  • Hexadecimal: "0x7B", "-0x7B"
  • Octal: "0173", "-0173"
  • Binary: "0b1111011", "-0b1111011"

Examples

// Positive number
num, _ := cast.Int("42") // 42

// Negative number
num, _ := cast.Int("-42") // -42

// Hexadecimal
num, _ := cast.Int32("0xFF") // 255
num, _ := cast.Int32("-0xFF") // -255

// Out of range returns error
_, err := cast.Int8("128") // Error: exceeds int8 range (-128 to 127)

Float Series - Floating-Point Conversion

Function Signatures

func Float32(s string) (float32, error)
func Float64(s string) (float64, error)

Description

Parses strings into corresponding floating-point types, using the standard library's strconv.ParseFloat internally.

Examples

// Regular floating-point
num, _ := cast.Float64("3.14") // 3.14
num, _ := cast.Float64("-2.5") // -2.5

// Scientific notation
num, _ := cast.Float64("1.23e-4") // 0.000123
num, _ := cast.Float64("1E6") // 1000000

// Special values
num, _ := cast.Float64("Inf") // +Inf
num, _ := cast.Float64("-Inf") // -Inf
num, _ := cast.Float64("NaN") // NaN

Decimal - High-Precision Decimal Conversion

Function Signature

func Decimal(s string) (decimal.Decimal, error)

Description

Parses strings into high-precision decimal values, using the github.com/shopspring/decimal package. Suitable for scenarios requiring exact calculations, such as financial computations.

Examples

import "github.com/shopspring/decimal"

// High-precision calculation
d1, _ := cast.Decimal("0.1")
d2, _ := cast.Decimal("0.2")
sum := d1.Add(d2) // Exact 0.3

// Avoid floating-point precision issues
// float64: 0.1 + 0.2 = 0.30000000000000004
// decimal: 0.1 + 0.2 = 0.3

Time - Time Conversion

Function Signature

func Time(s string) (time.Time, error)

Description

Parses strings into time.Time values. Supports multiple common time formats, including RFC standard formats, common date formats, and Unix timestamps.

Supported formats:

  • RFC3339: "2006-01-02T15:04:05Z07:00"
  • DateTime: "2006-01-02 15:04:05"
  • Date only: "2006-01-02"
  • Unix timestamp: "1703505045" (seconds)
  • With nanoseconds: "2006-01-02 15:04:05.999999999"
  • Other RFC formats: RFC1123, RFC822, etc.

Examples

// RFC3339 format
t, _ := cast.Time("2023-12-25T10:30:45Z")

// Common date formats
t, _ := cast.Time("2023-12-25")
t, _ := cast.Time("2023-12-25 10:30:45")
t, _ := cast.Time("2023/12/25")

// Unix timestamp
t, _ := cast.Time("1703505045") // 2023-12-25 10:30:45 UTC

// US date format
t, _ := cast.Time("12/25/2023")
t, _ := cast.Time("Dec 25, 2023")

// RFC formats
t, _ := cast.Time("Mon, 02 Jan 2006 15:04:05 MST")

Duration - Time Duration Conversion

Function Signature

func Duration(s string) (time.Duration, error)

Description

Parses strings into time.Duration values. Supports multiple input formats.

Supported formats:

  • Go standard format: "1h30m45s", "500ms", "2h"
  • Integer: treated as nanoseconds
  • Float: treated as seconds

Examples

// Go standard format
d, _ := cast.Duration("1h30m45s") // 1 hour 30 minutes 45 seconds
d, _ := cast.Duration("500ms") // 500 milliseconds
d, _ := cast.Duration("2h") // 2 hours

// Integer (nanoseconds)
d, _ := cast.Duration("1000000000") // 1 second (1 billion nanoseconds)

// Float (seconds)
d, _ := cast.Duration("1.5") // 1.5 seconds
d, _ := cast.Duration("0.001") // 1 millisecond

FromString - Generic Type Conversion

Function Signature

func FromString(s string, targetType string) (any, error)

Description

This wraps all type conversion functions, dynamically selecting the conversion function based on the type name string.

Supported type names:

  • Integers: "int", "int8", "int16", "int32", "int64"
  • Unsigned integers: "uint", "uint8", "uint16", "uint32", "uint64"
  • Floats: "float32", "float64"
  • Boolean: "bool"
  • String: "string"
  • Time: "time.Time", "time.Duration"

Examples

// Integer conversion
v, _ := cast.FromString("42", "int") // int(42)
v, _ := cast.FromString("255", "uint8") // uint8(255)

// Float conversion
v, _ := cast.FromString("3.14", "float64") // float64(3.14)

// Boolean conversion
v, _ := cast.FromString("true", "bool") // bool(true)

// String conversion
v, _ := cast.FromString("hello", "string") // string("hello")

// Time conversion
v, _ := cast.FromString("2023-12-25", "time.Time")
v, _ := cast.FromString("1h30m", "time.Duration")

// Unsupported type returns error
_, err := cast.FromString("42", "complex64") // Error: unsupported type

FromType - Reflection-Based Conversion

Function Signature

func FromType(s string, targetType reflect.Type) (any, error)

Description

This function converts the string s to the target type targetType and returns the corresponding value. Supports basic types and slice types.

Slice type support:

  • For slice types (like []int, []string), the input string is split by commas
  • Each element is trimmed and converted to the element type
  • Example: "1,2,3"[]int{1, 2, 3}

Examples

import "reflect"

// Basic type
t := reflect.TypeOf(0)
v, _ := cast.FromType("42", t) // int(42)

// Slice type
t := reflect.TypeOf([]int(nil))
v, _ := cast.FromType("1,2,3", t) // []int{1, 2, 3}

t := reflect.TypeOf([]string(nil))
v, _ := cast.FromType("a,b,c", t) // []string{"a", "b", "c"}

// Slice with spaces
v, _ := cast.FromType("1, 2, 3", t) // Automatically trims spaces
// Result: []int{1, 2, 3}

Use Cases

1. Configuration File Parsing

import "go-slim.dev/cast"

// Reading from environment variables or config files
port, _ := cast.Int(os.Getenv("PORT"))
debug, _ := cast.Bool(os.Getenv("DEBUG"))
timeout, _ := cast.Duration(os.Getenv("TIMEOUT"))

2. HTTP Parameter Processing

func handler(c slim.Context) error {
// Query parameter conversion
page, err := cast.Int(c.QueryParam("page"))
if err != nil {
return c.String(400, "Invalid page number")
}

limit, _ := cast.Int(c.QueryParam("limit"))

// ... use page and limit
}

3. Database Value Conversion

// String value read from database
var priceStr string
db.QueryRow("SELECT price FROM products WHERE id = ?", id).Scan(&priceStr)

// Convert to high-precision Decimal
price, _ := cast.Decimal(priceStr)

4. Command-Line Argument Parsing

import "flag"

var (
portStr = flag.String("port", "8080", "server port")
debugStr = flag.String("debug", "false", "debug mode")
)

func main() {
flag.Parse()

port, _ := cast.Int(*portStr)
debug, _ := cast.Bool(*debugStr)

// ... use port and debug
}

Error Handling

All conversion functions return error which should be handled appropriately:

// Basic error handling
num, err := cast.Int("abc")
if err != nil {
log.Printf("Conversion failed: %v", err)
return
}

// Using default value
num, err := cast.Int(input)
if err != nil {
num = 0 // Use default value
}

// Chained conversion
value := "42"
if num, err := cast.Int(value); err == nil {
// Use num
} else {
// Handle error
}

Performance Notes

  • All functions are thin wrappers over standard library functions with minimal performance overhead
  • No reflection is used (except for the FromType function)
  • Suitable for high-performance scenarios
  • Decimal type has additional performance overhead but provides exact decimal arithmetic

Notes

  1. Type range checking: Values exceeding the target type's range will return an error

    _, err := cast.Uint8("256")  // Error: out of range (0-255)
  2. Empty strings: Most functions will return an error for empty strings

    _, err := cast.Int("")       // Error
  3. String type: FromString("...", "string") always succeeds

    v, _ := cast.FromString("anything", "string")  // Always returns the original string
  4. Time formats: Time() tries multiple formats, selecting the first match

    t, _ := cast.Time("2023-12-25")              // Success
    t, _ := cast.Time("invalid") // Error
  5. Floating-point precision: Use Decimal instead of Float for financial calculations

    // Not recommended
    f, _ := cast.Float64("0.1")

    // Recommended (for financial scenarios)
    d, _ := cast.Decimal("0.1")