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:

var d float64 = 10.25  // a double number
var i int = int(d)  // casting the float64 to int

fmt.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:

import (
    "fmt"
    "strconv"
)

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

var ten int = 10  // an integer with value 10
var tenString string = strconv.Itoa(ten)  // converting int to string
fmt.Println("The value of tenString:", tenString)  // Output: The value of tenString: 10

var twentyFiveString string = "25"
var twentyFive int
twentyFive, _ = strconv.Atoi(twentyFiveString)  // converting string to int
fmt.Println("The value of twentyFive:", twentyFive)  // Output: The value of twentyFive: 25

var invalidNumber string = "25abc"
var number int
number, _ = 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.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal