Go•Type Conversion
Go Type Conversion and strconv Package (Atoi, Itoa)
Learn explicit type conversions in Go and parsing strings to numbers safely with strconv.
Syntax
val := int(floatVal)
num, err := strconv.Atoi("123")
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| strconv.Atoi | Function | ASCII to integer conversion returning (int, error). |
| strconv.Itoa | Function | Integer to ASCII string conversion. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Go locally:
package main
import (
"fmt"
"strconv"
)
func main() {
// 1. Primitive conversion
floatVal := 42.85
intVal := int(floatVal) // Truncates decimal
fmt.Printf("Float to int: %d (from %.2f)\n", intVal, floatVal)
// 2. String to integer parsing with strconv.Atoi
rawInput := "8080"
port, err := strconv.Atoi(rawInput)
if err != nil {
fmt.Println("Parse Error:", err)
return
}
fmt.Printf("Parsed port: %d (Port + 1 = %d)\n", port, port+1)
}Expected Output:
Float to int: 42 (from 42.85) Parsed port: 8080 (Port + 1 = 8081)
How It Works: Step-by-Step
- Lines 10-12: Explicit int(floatVal) cast truncates decimal.
- Lines 15-17: strconv.Atoi converts string to int and returns error check.
Key Concepts
- In Go, all conversions are explicit: T(v).
- strconv.Atoi returns both the parsed integer and an error object.
Common Mistake: Using string(int) expecting string representation "65"
In Go, string(65) converts the integer to ASCII character "A", NOT the string "65"!
❌ Incorrect
s := string(65) // Evaluates to "A", not "65"!
✅ Correct
s := strconv.Itoa(65) // Evaluates to "65"
Related Go Tutorials & Compiler
Go Short Variable Declaration Operator (:=) and Scoping Mechanics
Master Go short variable declaration operator (:=), local function scope restrictions, type inference, and multi-variable assignments.
Go Operators: Arithmetic, Comparison, and Bitwise Logic
Explore arithmetic, logical (&&, ||), comparison, and bitwise operators in Go.
Go If Statements with Inline Variable Initialization and Scope Limiting
Master Go if statements with compact inline variable initialization (if init; condition), keeping variables tightly scoped to branch blocks.
Go Online Compiler
Open in Compilra IDE
Run and test Go on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.