Go Type Conversions
Go is statically typed and very strict. It never performs "implicit" conversions (e.g., adding an int to a float64 automatically). You must always be explicit.
1. Numeric Conversions
To convert between numbers, use the type name as a function.
Warning: Converting a float64(3.9) to an int will result in 3 (truncation), not 4.
2. String Conversions (strconv)
Converting a number to a string (or vice versa) requires the strconv package.
3. Type Assertions (Interfaces)
A type assertion provides access to an interface value's underlying concrete value.
4. Type Switches
A type switch is a cleaner way to handle multiple possible types for an interface.
Why is Go so strict?
- Safety: Prevents hidden bugs where precision is lost or numbers overflow without you noticing.
- Clarity: By forcing you to write
int64(x), the code clearly communicates that a conversion is happening.