Type Conversion
Start with Go Type Conversion
A type conversion creates a value in a different compatible type. Go normally requires explicit conversions between distinct numeric types instead of silently mixing them.
What you’ll learn
- Convert between numeric types.
- Recognize truncation behavior.
- Parse text with strconv and check errors.
Understand the idea
Write float64(count) to convert an integer into a floating-point value. Converting a floating-point variable with int(value) discards the fractional part; it does not round. A non-integral constant such as int(7.9) is rejected by the compiler.
Converting a string that contains digits into a number is not done by int("42"). Use parsing functions such as strconv.Atoi and handle the returned error. Conversion and parsing are distinct operations.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"strconv"
)
func main() {
count := 5
average := float64(count) / 2
fraction := 7.9
whole := int(fraction)
parsed, err := strconv.Atoi("42")
fmt.Println("Average:", average)
fmt.Println("Whole:", whole)
fmt.Println("Parsed:", parsed, "Error:", err)
}
Output
Average: 2.5
Whole: 7
Parsed: 42 Error: <nil>Trace what the program does
The first conversion allows floating-point division and returns 2.5. The second produces 7 by truncating toward zero. Atoi parses the text "42" as an integer and returns nil for the error.
Avoid common mistakes
- Go does not automatically convert between
intandfloat64in ordinary expressions. - Do not ignore parsing errors when handling external input; invalid text may fail to parse.
Try it yourself
Change "42" to "42x". Print and inspect the error rather than treating the parsed value as valid.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Go Type Conversion in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.