Go supports explicit type conversions but not implicit ones. This means that developers must explicitly specify the new type when conversion is required. Go does not allow direct assignment between different types; even for conversions such as from int to float, explicit conversion is required.
Example: Converting Integers to Floating-Point Numbers
Assume we have an integer a, and we need to convert it to a floating-point number b. The code is as follows:
gopackage main import ( "fmt" ) func main() { a := 42 b := float64(a) fmt.Printf("Integer: %d converted to floating-point: %f\n", a, b) }
In this code, a is an integer (int), and b is obtained through explicit conversion using float64(a), resulting in a floating-point type (float64). fmt.Printf is used to output the values before and after conversion.
This explicit conversion ensures type safety and helps avoid runtime issues caused by type errors. In actual development, correctly and clearly using type conversions is a crucial part, helping to improve code maintainability and readability.