Working with Type Conversion in Go

12.01.2021

Intro

Type conversion lets you easily change the types of your variables in Go. We can do this using the cast operator. In this article, we will learn how to use type conversion in Go.

The Case Operator

The cast operator has the following format:

type_name(variable)

For example, if we want to convert an int to a float32 we can do the following.

num := 15

float_num = float32(num) // Turn num into a float
fmt.Println(float_num)

Other Type Conversions

Not all type casting will work as expected. For example, we get an odd character when doing the following:

string_num := string(num)
fmt.Println(string_num)

For some type conversions, we will need to use libraries. We can use strconv to convert an integer to a character using the Itoa method.

fmt.Println(strconv.Itoa(num))

Of course, we can also use the Sprintf string format method to convert items to strings as well.

Here %d represents that we want to convert an integer, which matches our first argument, num. For a full list of "verbs" or formatters, check the docs here: https://pkg.go.dev/fmt

s := fmt.Sprintf("The integer is: %d", num)
fmt.Println(s)

Full Example

You can run the full example code by copying the code below to a file called main.go and run go run main.go

package main

import (
	"fmt"
	"strconv"
)

func main() {
	num := 15

	float_num := float32(num)
	fmt.Println(float_num)

	string_num := string(num)
	fmt.Println(string_num)

	fmt.Println(strconv.Itoa(num))

	s := fmt.Sprintf("The integer is: %d", num)
	fmt.Println(s)
}