In this guide, you’ll learn how to perform type conversion (also known as type casting) in Go by converting variables from one data type to another. While converting variables is straightforward, be aware that the actual value may change after conversion due to differences in data representation.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Converting an Integer to a Float
Converting an integer to a floating-point number in Go is simple. You can convert an integer by wrapping it with the desired float type (either float64 or float32). For example, consider the following Go program. It declares an integer variable i, converts it to a float64 stored in variable f, and then prints the result.
When converting an integer to a float, the numeric value remains the same, but may be represented differently with added precision.
Converting a Float to an Integer
Go also allows you to convert a floating-point number to an integer. This conversion will truncate the decimal portion, losing any fractional precision. Consider this example:Keep in mind that converting a float to an integer results in a loss of precision. Ensure this behavior is acceptable for your application’s use case.
String Conversion with the strconv Package
Go’s built-in package,strconv, makes it easy to convert between strings and integers. Two frequently used functions in this package are:
Itoa: Converts an integer to a string.Atoi: Converts a string to an integer and returns both the integer value and an error if the conversion fails.
Converting an Integer to a String
To convert an integer to a string, import thestrconv package and use the Itoa function. The code below demonstrates this conversion:
"42" verifies that the conversion from integer to string was successful.
Converting a String to an Integer
To convert a string to an integer, use theAtoi function, which returns both the converted integer and an error value. When the string represents a valid integer, the error will be nil.
For example, consider this conversion of a valid string:
strconv package comes equipped with helpful functions like Itoa and Atoi for converting between types, with built-in error handling to ensure the conversion is successful.
