Go by Example: Type Conversion
Go is a strongly typed language and does not support implicit type conversion. This example shows how to explicitly convert between types like int, float, and string using direct casting and the `strconv` package.
Code
package main
import (
"fmt"
"strconv"
)
func main() {
// 1. Numeric Conversions
// You must explicitly convert between numeric types.
var i int = 42
var f float64 = float64(i)
var u uint = uint(f)
fmt.Printf("int: %d, float: %.2f, uint: %d\n", i, f, u)
// 2. String to Integer (Parsing)
// Use strconv.Atoi (ASCII to Integer)
str1 := "123"
num1, err := strconv.Atoi(str1)
if err != nil {
fmt.Println("Error converting string:", err)
} else {
fmt.Println("Parsed integer:", num1)
}
// 3. Integer to String (Formatting)
// Use strconv.Itoa (Integer to ASCII)
num2 := 456
str2 := strconv.Itoa(num2)
fmt.Printf("Formatted string: %q (type: %T)\n", str2, str2)
// 4. Parse specific sizes/bases
// ParseInt allows specifying base (10, 16, etc.) and bit size (32, 64)
hexStr := "1A"
val, _ := strconv.ParseInt(hexStr, 16, 64)
fmt.Printf("Parsed hex '%s' to decimal: %d\n", hexStr, val)
// 5. Common Pitfall: string(int)
// Converting an int directly to a string interprets it as a rune (Unicode code point),
// NOT the decimal representation.
myInt := 65
myStr := string(myInt) // Becomes "A", not "65"
fmt.Println("string(65) result:", myStr)
}
Explanation
Unlike C or Java, Go does not support implicit type conversion (coercion). You cannot simply assign an int variable to a float64 variable; you must explicitly convert it using the syntax Type(value). This strictness prevents a whole class of bugs related to accidental precision loss or overflow.
For converting between numbers and strings, simple casting doesn't work the way you might expect (e.g., string(65) produces "A", not "65"). Instead, you use the strconv package. strconv.Atoi parses a string to an int, and strconv.Itoa formats an int to a string. For more complex parsing (like hex or binary), use strconv.ParseInt.
- Numeric Casting:
float64(i),int(f). Truncates decimals when converting float to int. - Parsing:
strconv.Atoi("100")returns(int, error). - Formatting:
strconv.Itoa(100)returnsstring. - Gotcha:
string(int)converts to a Unicode character, not text digits.

