cast Module The cast module provides comprehensive type conversion functions with robust error handling, making it easy to convert between different data types safely and predictably.
Functions ToString(value) Converts any value to its string representation.
Parameters: - value: The value to convert to string (any type)
Returns: - (string, error): String representation of the value
Examples:
ToString Examples package main
import fmt
import cast
var str1, err1 = cast.ToString(42) // "42"
var str2, err2 = cast.ToString(3.14) // "3.14"
var str3, err3 = cast.ToString(true) // "true"
var str4, err4 = cast.ToString(None) // "None"
var str5, err5 = cast.ToString({"a": 1}) // "{a: 1}"
var bigStr, errBig = cast.ToString(bigint("12345678901234567890")) // "12345678901234567890"
var decStr, errDec = cast.ToString(bigdecimal("1/3")) // "1/3"
fmt.Printf("Number: %s\n", str1)
fmt.Printf("Float: %s\n", str2)
fmt.Printf("Boolean: %s\n", str3)
fmt.Printf("BigInt: %s\n", bigStr)
fmt.Printf("BigDecimal: %s\n", decStr)
ToRune(value) Converts a value to a Unicode code point (rune) represented as an integer.
Parameters: - value: A single-character string (e.g., "A") or an integer code point (0..0x10FFFF)
Returns: - (int, error): The Unicode code point integer, or an error on invalid input.
Conversion Rules: - String: Must contain exactly one Unicode character - Integer: Must be within 0..0x10FFFF
Example:
ToRune Example package main
import fmt
import cast
var cp, err = cast.ToRune("A") // 65
if err == None {
fmt.Printf("%d\n", cp)
}
ToInt(value) Converts a value to an integer with validation.
Parameters: - value: The value to convert (string, float, boolean, or integer)
Returns: - (int, error): Integer representation of the value
Conversion Rules: - String : Must be a valid integer format - Float : Truncates decimal part - Boolean : true → 1, false → 0 - Integer : Returns as-is - BigInt : Only if the value fits into int64, otherwise returns an error - BigDecimal : Only if the value is an integer (denominator 1) and fits into int64, otherwise returns an error - None : Returns error
Examples:
ToInt Examples package main
import fmt
import cast
var int1, err1 = cast.ToInt("123") // 123
var int2, err2 = cast.ToInt(3.14) // 3
var int3, err3 = cast.ToInt(true) // 1
var int4, err4 = cast.ToInt(false) // 0
// From bigint (within int64 range)
var bigOk, errBigOk = cast.ToInt(bigint("42"))
// From bigint (out of int64 range)
var bigTooLarge, errBigTooLarge = cast.ToInt(bigint("123456789012345678901234567890"))
// From bigdecimal integer value
var decOk, errDecOk = cast.ToInt(bigdecimal("10")) // 10
// From bigdecimal non-integer value (error)
var decBad, errDecBad = cast.ToInt(bigdecimal("10.5")) // error
// Error handling
var invalid, err5 = cast.ToInt("hello")
if err5 != None {
fmt.Printf("Conversion failed: %s\n", err5)
}
if errBigTooLarge != None {
fmt.Printf("BigInt out of range: %s\n", errBigTooLarge)
}
ToFloat(value) Converts a value to a floating-point number.
Parameters: - value: The value to convert (string, integer, boolean, or float)
Returns: - (float, error): Float representation of the value
Conversion Rules: - String : Must be a valid float format - Integer : Converts to equivalent float - Boolean : true → 1.0, false → 0.0 - Float : Returns as-is - BigInt : Converts to float64 via big.Float; may lose precision or overflow to +Inf/-Inf - BigDecimal : Converts to float64 via big.Rat.Float64; may lose precision for repeating/non-terminating decimals - None : Returns error
Examples:
ToFloat Examples package main
import fmt
import cast
var float1, err1 = cast.ToFloat("3.14159") // 3.14159
var float2, err2 = cast.ToFloat(42) // 42.0
var float3, err3 = cast.ToFloat(true) // 1.0
var bigFloat, errBig = cast.ToFloat(bigint("12345678901234567890"))
var decFloat, errDec = cast.ToFloat(bigdecimal("0.1"))
fmt.Printf("Pi: %s\n", float1)
fmt.Printf("Answer: %s\n", float2)
fmt.Printf("BigInt as float: %s (may lose precision)\n", bigFloat)
fmt.Printf("BigDecimal 0.1 as float: %s\n", decFloat)
ToBool(value) Converts a value to a boolean with flexible conversion rules.
Parameters: - value: The value to convert (any type)
Returns: - (bool, error): Boolean representation of the value
Conversion Rules: - String : - "true", "1", "yes", "on" → true - "false", "0", "no", "off", "" → false - Case-insensitive - Numbers (int, float, bigint, bigdecimal) : numeric zero (0, 0.0, bigint(0), bigdecimal(0)) → false, any other numeric value → true - None : → false - Arrays/Maps : empty → false, non-empty → true - Boolean : Returns as-is
Examples:
ToBool Examples package main
import fmt
import cast
var bool1, err1 = cast.ToBool("true") // true
var bool2, err2 = cast.ToBool("yes") // true
var bool3, err3 = cast.ToBool("1") // true
var bool4, err4 = cast.ToBool(0) // false
var bool5, err5 = cast.ToBool([]) // false (empty array)
var bool6, err6 = cast.ToBool([1, 2]) // true (non-empty array)
var bigBoolTrue, errBig1 = cast.ToBool(bigint("1")) // true
var bigBoolFalse, errBig2 = cast.ToBool(bigint("0")) // false
var decBoolTrue, errDec1 = cast.ToBool(bigdecimal("1/3")) // true
var decBoolFalse, errDec2 = cast.ToBool(bigdecimal("0")) // false
fmt.Printf("String to bool: %s\n", bool1)
fmt.Printf("Array to bool: %s\n", bool6)
fmt.Printf("BigInt 1 to bool: %s\n", bigBoolTrue)
fmt.Printf("BigInt 0 to bool: %s\n", bigBoolFalse)
fmt.Printf("BigDecimal 1/3 to bool: %s\n", decBoolTrue)
fmt.Printf("BigDecimal 0 to bool: %s\n", decBoolFalse)
ToArray(value) Converts a value to an array.
Parameters: - value: The value to convert (string, map, or array)
Returns: - (array, error): Array representation of the value
Conversion Rules: - String : Converts to array of characters - Map : Converts to array of [key, value] pairs - Array : Returns as-is - Other types : Returns error
Examples:
ToArray Examples package main
import fmt
import cast
var arr1, err1 = cast.ToArray("hello") // ["h", "e", "l", "l", "o"]
var arr2, err2 = cast.ToArray({"a": 1, "b": 2}) // [["a", 1], ["b", 2]]
var arr3, err3 = cast.ToArray([1, 2, 3]) // [1, 2, 3]
fmt.Printf("String to array: %s\n", arr1)
fmt.Printf("Map to array: %s\n", arr2)
ToMap(value) Converts a value to a map.
Parameters: - value: The value to convert (array of pairs or map)
Returns: - (map, error): Map representation of the value
Conversion Rules: - Array : Must be array of [key, value] pairs with hashable keys - Map : Returns as-is - Other types : Returns error
Hashable Keys: Strings, integers, and booleans
Examples:
ToMap Examples package main
import fmt
import cast
var map1, err1 = cast.ToMap([["a", 1], ["b", 2], ["c", 3]]) // {"a": 1, "b": 2, "c": 3}
var map2, err2 = cast.ToMap({"x": 10, "y": 20}) // {"x": 10, "y": 20}
// Error case - invalid structure
var invalid, err3 = cast.ToMap([1, 2, 3]) // Error: not pairs
if err3 != None {
fmt.Printf("Conversion failed: %s\n", err3)
}
fmt.Printf("Array to map: %s\n", map1)
CanCast(value, targetType) Checks if a value can be cast to a specific type without performing the conversion.
Parameters: - value: The value to check - targetType: Target type as string ("string", "int", "float", "bool", "array", "map")
Returns: - (bool, error): true if casting is possible, false otherwise
Examples:
CanCast Examples package main
import fmt
import cast
var canCast1, err1 = cast.CanCast("42", "int") // true
var canCast2, err2 = cast.CanCast("hello", "int") // false
var canCast3, err3 = cast.CanCast([1, 2], "array") // true
var canCast4, err4 = cast.CanCast("anything", "string") // true (everything can be string)
// BigInt-specific checks
var canBigIntToInt, errBig1 = cast.CanCast(bigint("42"), "int") // true
var canBigIntTooLarge, errBig2 = cast.CanCast(bigint("12345678901234567890"), "int") // false (out of int64 range)
var canBigIntToFloat, errBig3 = cast.CanCast(bigint("12345678901234567890"), "float") // true
var canBigIntToBool, errBig4 = cast.CanCast(bigint("0"), "bool") // true
// BigDecimal-specific checks
var canDecIntExact, errDec1 = cast.CanCast(bigdecimal("10"), "int") // true
var canDecIntNonExact, errDec2 = cast.CanCast(bigdecimal("10.5"), "int") // false (not an integer)
var canDecFloat, errDec3 = cast.CanCast(bigdecimal("1/3"), "float") // true
var canDecBool, errDec4 = cast.CanCast(bigdecimal("0"), "bool") // true
// Use before casting to avoid errors
if canCast1 {
var num, _ = cast.ToInt("42")
fmt.Printf("Converted: %s\n", num)
}
fmt.Printf("Can cast '42' to int: %s\n", canCast1)
fmt.Printf("Can cast 'hello' to int: %s\n", canCast2)
fmt.Printf("Can cast bigint('42') to int: %s\n", canBigIntToInt)
fmt.Printf("Can cast large bigint to int: %s\n", canBigIntTooLarge)
Type Conversion Matrix From Type To String To Int To Float To Bool To Array To Map String ✅ Always ✅ If valid ✅ If valid ✅ Flexible rules ✅ To chars ❌ No Integer ✅ Always ✅ Always ✅ Always ✅ 0→false, other→true ❌ No ❌ No Float ✅ Always ✅ Truncate ✅ Always ✅ 0.0→false, other→true ❌ No ❌ No Boolean ✅ Always ✅ 1/0 ✅ 1.0/0.0 ✅ Always ❌ No ❌ No BigInt ✅ Always ✅ If within int64 range ✅ Always (precision may be lost) ✅ 0→false, other→true ❌ No ❌ No BigDecimal ✅ Always ✅ If integer & in int64 range ✅ Always (precision may be lost) ✅ 0→false, other→true ❌ No ❌ No Array ✅ Always ❌ No ❌ No ✅ Empty→false, non-empty→true ✅ Always ✅ If pairs Map ✅ Always ❌ No ❌ No ✅ Empty→false, non-empty→true ✅ To pairs ✅ Always None ✅ "None" ❌ Error ❌ Error ✅ false ❌ Error ❌ Error
Error Handling The cast module provides detailed error messages for failed conversions:
Error Handling package main
import fmt
import cast
// Invalid string to integer
var result, err = cast.ToInt("not_a_number")
if err != None {
fmt.Printf("Error: %s\n", err)
// Output: Error: cast.ToInt: cannot convert string "not_a_number" to integer: strconv.ParseInt: parsing "not_a_number": invalid syntax
}
// Invalid array to map (not pairs)
var mapResult, mapErr = cast.ToMap([1, 2, 3])
if mapErr != None {
fmt.Printf("Error: %s\n", mapErr)
// Output: Error: cast.ToMap: array element 0 is not an array (expected [key, value] pairs)
}
// Unsupported conversion
var boolResult, boolErr = cast.ToBool("maybe")
if boolErr != None {
fmt.Printf("Error: %s\n", boolErr)
// Output: Error: cast.ToBool: cannot convert string "maybe" to boolean (valid values: true/false, 1/0, yes/no, on/off)
}
Common Use Cases Data Validation and Conversion Data Validation package main
import fmt
import cast
function processUserInput(input string, expectedType string) {
var canConvert, _ = cast.CanCast(input, expectedType)
if !canConvert {
fmt.Printf("Invalid input: cannot convert '%s' to %s\n", input, expectedType)
return
}
if expectedType == "int" {
var value, err = cast.ToInt(input)
if err == None {
fmt.Printf("Processing integer: %s\n", value)
}
} else if expectedType == "float" {
var value, err = cast.ToFloat(input)
if err == None {
fmt.Printf("Processing float: %s\n", value)
}
}
}
processUserInput("42", "int") // Processing integer: 42
processUserInput("hello", "int") // Invalid input: cannot convert 'hello' to int
Configuration Processing Configuration Processing package main
import fmt
import cast
function parseConfig(configMap map) {
// Convert string values to appropriate types
var portStr = configMap["port"]
var port, portErr = cast.ToInt(portStr)
var enabledStr = configMap["enabled"]
var enabled, enabledErr = cast.ToBool(enabledStr)
if portErr == None && enabledErr == None {
fmt.Printf("Server config - Port: %s, Enabled: %s\n", port, enabled)
}
}
var config = {"port": "8080", "enabled": "true"}
parseConfig(config) // Server config - Port: 8080, Enabled: true
Data Transformation package main
import fmt
import cast
function main() {
// Transform map to array of entries format
var csvData = [["name", "age"], ["Alice", "25"], ["Bob", "30"]]
var headers = csvData[0]
var rows = csvData[1:]
var records = []
for row in rows {
var record = {}
for i, value in row {
var header = headers[i]
if header == "age" {
var ageInt, _ = cast.ToInt(value)
record[header] = ageInt
} else {
record[header] = value
}
var record = {}
for i, value in row {
var header = headers[i]
if header == "age" {
var ageInt, _ = cast.ToInt(value)
record[header] = ageInt
} else {
record[header] = value
}
}
records = append(records, record)
}
fmt.Printf("Structured data: %s\n", records)
// Output: Structured data: [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]
Integration with Other Modules JSON and Cast Integration JSON Integration package main
import fmt
import json
import cast
// Parse JSON and convert specific fields
var jsonStr = "{\"id\": \"123\", \"active\": \"true\", \"score\": \"95.5\"}"
var data, _ = json.Unmarshal(jsonStr)
var id, _ = cast.ToInt(data["id"])
var active, _ = cast.ToBool(data["active"])
var score, _ = cast.ToFloat(data["score"])
var processedData = {
"id": id,
"active": active,
"score": score
}
fmt.Printf("Processed: %s\n", processedData)
// Output: Processed: {"id": 123, "active": true, "score": 95.5}
OS and Cast Integration OS Integration package main
import fmt
import os
import cast
// Convert environment variables to appropriate types
var portEnv, _ = os.Getenv("PORT")
var debugEnv, _ = os.Getenv("DEBUG")
var port, portErr = cast.ToInt(portEnv)
var debug, debugErr = cast.ToBool(debugEnv)
if portErr == None && debugErr == None {
fmt.Printf("Config - Port: %s, Debug: %s\n", port, debug)
}
See Also