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/castQuick Start
package mainimport ( "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 truecast.Bool("true")cast.Bool("TRUE")cast.Bool("1")cast.Bool("t")// Returns falsecast.Bool("false")cast.Bool("FALSE")cast.Bool("0")cast.Bool("f")// Returns errorcast.Bool("yes") // Unsupported valuecast.Bool("no") // Unsupported valueUint 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
// Decimalnum, _ := cast.Uint("123") // 123num8, _ := cast.Uint8("255") // 255// Hexadecimalnum, _ := cast.Uint("0xFF") // 255// Octalnum, _ := cast.Uint("0777") // 511// Binarynum, _ := cast.Uint("0b1010") // 10// Out of range returns error_, err := cast.Uint8("256") // Error: exceeds uint8 rangeInt 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 numbernum, _ := cast.Int("42") // 42// Negative numbernum, _ := cast.Int("-42") // -42// Hexadecimalnum, _ := cast.Int32("0xFF") // 255num, _ := 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-pointnum, _ := cast.Float64("3.14") // 3.14num, _ := cast.Float64("-2.5") // -2.5// Scientific notationnum, _ := cast.Float64("1.23e-4") // 0.000123num, _ := cast.Float64("1E6") // 1000000// Special valuesnum, _ := cast.Float64("Inf") // +Infnum, _ := cast.Float64("-Inf") // -Infnum, _ := cast.Float64("NaN") // NaNDecimal - 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 calculationd1, _ := 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.3Time - 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 formatt, _ := cast.Time("2023-12-25T10:30:45Z")// Common date formatst, _ := cast.Time("2023-12-25")t, _ := cast.Time("2023-12-25 10:30:45")t, _ := cast.Time("2023/12/25")// Unix timestampt, _ := cast.Time("1703505045") // 2023-12-25 10:30:45 UTC// US date formatt, _ := cast.Time("12/25/2023")t, _ := cast.Time("Dec 25, 2023")// RFC formatst, _ := 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 formatd, _ := cast.Duration("1h30m45s") // 1 hour 30 minutes 45 secondsd, _ := cast.Duration("500ms") // 500 millisecondsd, _ := 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 secondsd, _ := cast.Duration("0.001") // 1 millisecondFromString - 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 conversionv, _ := cast.FromString("42", "int") // int(42)v, _ := cast.FromString("255", "uint8") // uint8(255)// Float conversionv, _ := cast.FromString("3.14", "float64") // float64(3.14)// Boolean conversionv, _ := cast.FromString("true", "bool") // bool(true)// String conversionv, _ := cast.FromString("hello", "string") // string("hello")// Time conversionv, _ := cast.FromString("2023-12-25", "time.Time")v, _ := cast.FromString("1h30m", "time.Duration")// Unsupported type returns error_, err := cast.FromString("42", "complex64") // Error: unsupported typeFromType - 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 typet := reflect.TypeOf(0)v, _ := cast.FromType("42", t) // int(42)// Slice typet := 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 spacesv, _ := 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 filesport, _ := 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 databasevar priceStr stringdb.QueryRow("SELECT price FROM products WHERE id = ?", id).Scan(&priceStr)// Convert to high-precision Decimalprice, _ := 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 handlingnum, err := cast.Int("abc")if err != nil { log.Printf("Conversion failed: %v", err) return}// Using default valuenum, err := cast.Int(input)if err != nil { num = 0 // Use default value}// Chained conversionvalue := "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
FromTypefunction) - Suitable for high-performance scenarios
Decimaltype has additional performance overhead but provides exact decimal arithmetic
Notes
-
Type range checking: Values exceeding the target type’s range will return an error
_, err := cast.Uint8("256") // Error: out of range (0-255) -
Empty strings: Most functions will return an error for empty strings
_, err := cast.Int("") // Error -
String type:
FromString("...", "string")always succeedsv, _ := cast.FromString("anything", "string") // Always returns the original string -
Time formats:
Time()tries multiple formats, selecting the first matcht, _ := cast.Time("2023-12-25") // Successt, _ := cast.Time("invalid") // Error -
Floating-point precision: Use
Decimalinstead ofFloatfor financial calculations// Not recommendedf, _ := cast.Float64("0.1")// Recommended (for financial scenarios)d, _ := cast.Decimal("0.1")