Lesson 6

Understanding Data Type Conversion in Go

Topic Overview

Greetings! Are you ready to delve deeper into the universe of the Go language? Our current journey delves into a fundamental concept of programming languages: Data Type Conversion. Often, we need to transform one data type into another, similar to adjusting a spaceship's asteroid-floating-point measurements to fit the integer-based radar system. We will study both automatic and explicit conversions, pointing out potential traps and loopholes along the way. Let's power up our knowledge engines!

Automatic (Implicit) Conversions

Unlike many other languages, Go does not provide automatic type conversions. Consequently, each conversion between different types requires explicit syntax. This might seem restrictive, but the approach is designed to prevent subtle bugs.

Manual (Explicit) Conversions

There will be instances when we will need to fit a large floating-point number into an integer-based tuple, requiring explicit casting. Observe how we convert a float64 to an int:

1var d float64 = 10.25 // a double number 2var i int = int(d) // casting the float64 to int 3 4fmt.Println("The value of i:", i) // Output: The value of i: 10

Notice that the fractional part 0.25 was discarded during the process, leaving only 10 as the result.

Converting to and from Strings: Integer

A type of conversion that frequently occurs in Go is converting to and from string values. We often need to convert numbers to strings for output or parse strings as numbers for calculations. Note that you will need to import "strconv" to use functions for strings conversion. It will look like this:

1import ( 2 "fmt" 3 "strconv" 4)

Now, let's meet our string conversion functions in the following code snippet.

1var ten int = 10 // an integer with value 10 2var tenString string = strconv.Itoa(ten) // converting int to string 3fmt.Println("The value of tenString:", tenString) // Output: The value of tenString: 10 4 5var twentyFiveString string = "25" 6var twentyFive int 7twentyFive, _ = strconv.Atoi(twentyFiveString) // converting string to int 8fmt.Println("The value of twentyFive:", twentyFive) // Output: The value of twentyFive: 25 9 10var invalidNumber string = "25abc" 11var number int 12number, _ = strconv.Atoi(invalidNumber) // Oops! This will throw an error, "25abc" is not a number!

For the conversion from string to int, we use strconv.Itoa(i), and for the conversion from string to int, we use strconv.Atoi(s). The last one returns two values: the converted string, and an error message if something goes wrong. That's why we assign it to two variables, twentyFive, _, where twentyFive will hold our value, and _ will hold the error. Without error, _ will simply contain nil. By naming error _, we highlight that we do not plan to use this error message, even if it is not empty.

Converting to and from Strings: Float

You may want to convert strings to float64 numbers, or the other way around. Here is how to do it in Go:

1var pi float64 = 3.14159 // a float value 2 3// coverting float to string 4var piString string = strconv.FormatFloat(pi, 'f', -1, 64) 5fmt.Println("The value of piString:", piString) // Output: The value of piString: 3.14159 6 7var invalidFloatString string = "3.14abc" 8var number float64 9number, _ = strconv.ParseFloat(invalidFloatString, 64) // This will throw an error!

In strconv.FormatFloat(f, 'f', -1, 64), 'f' is the format, -1 allows any precision, and 64 specifies the bit size.

In strconv.ParseFloat(s, 64), 64 is the bit size for the resultant floating-point number.

The strconv functions will return an error if the string is not a valid number. So, ensure your inputs are correctly formatted.

Lesson Summary and Practice

Congratulations! You've now mastered Data Type Conversion in Go! You've learned that Go doesn't perform automatic type conversions to ensure explicitness and a bug-free environment.

Now, why not translate this theoretical knowledge into practical skills with some programming exercises? Practice is the launchpad that allows your newly acquired knowledge to soar to greater heights!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.