What is Type Conversion in Go: Simple Explanation and Example
type conversion means changing a value from one data type to another explicitly using syntax like Type(value). It helps you work with different types safely and clearly in your code.How It Works
Type conversion in Go is like changing the shape of a puzzle piece so it fits into a different spot. Imagine you have a number stored as a whole number (int), but you need it as a decimal number (float64) to do precise calculations. You tell Go to convert that number explicitly so it fits the new role.
Unlike some languages that change types automatically, Go requires you to be clear and direct about conversions. This avoids surprises and keeps your program safe and predictable. You write the new type name followed by the value in parentheses, and Go creates a new value of that type.
Example
This example shows converting an integer to a float64 to perform division with decimals.
package main import "fmt" func main() { var a int = 5 var b int = 2 // Without conversion, division is integer division result1 := a / b // With conversion, convert 'a' and 'b' to float64 for decimal division result2 := float64(a) / float64(b) fmt.Println("Integer division result:", result1) fmt.Println("Float division result:", result2) }
When to Use
Use type conversion in Go when you need to work with different data types together, like numbers and decimals, or when calling functions that expect a specific type. For example, converting an int to float64 before division to get a precise result, or converting a byte to rune when working with characters.
It is also useful when reading data from external sources like files or user input, where the data type might not match what your program expects. Being explicit with conversions helps avoid bugs and makes your code easier to understand.
Key Points
- Type conversion in Go is explicit and uses
Type(value)syntax. - It creates a new value of the target type without changing the original.
- Go does not perform automatic type conversions to keep code safe.
- Commonly used to convert between numeric types or between bytes and runes.
- Helps avoid errors and makes code intentions clear.