candy - Type Conversion
Overview
The candy module provides high-performance type conversion utilities with zero-allocation optimizations. It supports conversion between various Go types including strings, numbers, booleans, slices, and maps.
Integer Conversion Functions
ToInt()
Convert any type to int.
Supported Types:
- bool: true → 1, false → 0
- All integer types (int, int8, int16, int32, int64)
- All unsigned integer types (uint, uint8, uint16, uint32, uint64)
- Float types (float32, float64)
- string, []byte: Parsed as integer
- Other types: Returns 0
Example:
ToInt8(), ToInt16(), ToInt32(), ToInt64()
Convert to specific integer types.
Example:
ToUint(), ToUint8(), ToUint16(), ToUint32(), ToUint64()
Convert to unsigned integer types.
Example:
Float Conversion Functions
ToFloat(), ToFloat32(), ToFloat64()
Convert to float types.
Supported Types:
- bool: true → 1.0, false → 0.0
- All integer types
- Float types
- string, []byte: Parsed as float
- Other types: Returns 0.0
Example:
Boolean Conversion
ToBool()
Convert any type to boolean.
Supported Types:
- bool: Returns as-is
- Numbers: Non-zero → true, zero → false
- string, []byte: "1", "true", "yes", "on" → true
- Other types: Returns false
Example:
String Conversion
ToString()
Convert any type to string.
Supported Types:
- bool: true → "1", false → "0"
- All integer types: Converted to decimal string
- Float types: Converted with appropriate precision
- time.Duration: Formatted as duration string
- string: Returns as-is
- []byte: Converted to string
- nil: Returns ""
- error: Returns error message
- Other types: JSON serialized
Example:
Slice Conversion
ToSlice()
Convert any type to slice.
Supported Types:
- Arrays and slices of any type
- Maps: Converted to slice of values
- Other types: Wrapped in single-element slice
Example:
ToIntSlice(), ToStringSlice(), etc.
Convert to typed slices.
Example:
Map Conversion
ToMap()
Convert any type to map.
Supported Types:
- map[string]interface{}: Returns as-is
- map[interface{}]interface{}: Keys converted to strings
- Struct: Fields converted to map entries
- Other types: Returns empty map
Example:
Pointer Conversion
ToPtr()
Convert any type to pointer.
Example:
Usage Patterns
HTTP Request Parsing
Configuration Parsing
Data Processing
Database Operations
Performance Characteristics
Zero-Allocation Conversions
The candy module is optimized for performance with zero-allocation conversions where possible:
Benchmarks
Best Practices
Type Safety
Error Handling
Related Documentation
- stringx - String utilities
- anyx - Interface{} helpers
- API Documentation
- Module Overview