How to Convert Golang int64 to String

The strconv package provides functions and utilities that help us convert from and to string values. Go provides an int data type that can be declared as an int which will only store signed numeric values. An integer can be int, int64, or int128. 

In this article, we will go through what int64 is and how to convert it into a string.

What is int64?

An int64 is an immutable value representing signed integers with values ranging from negative 9,223,372,036,854,775,808 to positive 9,223,372,036,854,775,807.

The int size is implementation-specific; it’s either 32 or 64 bits; hence, you won’t lose any information when converting from int to  int64.

How to define int64 in Golang

To define and declare an int64 variable in Go, use the var variable_name int64 syntax.

 var num int64 = 10
 fmt.Print(reflect.TypeOf(num), "\n")

Output

int64

In this tutorial, we will convert an int64 to a string data type.

Golang int64 to String

To convert int64 to string in Golang, use the strconv.FormatInt() function. The FormatInt() is a built-in function that returns a string representation of a given integer in a chosen base, ranging from 2 to 36).  The FormatInt() function accepts an integer and base as arguments and returns a string representation of int64.

package main

import (
  "fmt"
  "reflect"
  "strconv"
)

func main() {
  var num int64 = 10
  fmt.Print(reflect.TypeOf(num), "\n")
  str := strconv.FormatInt(num, 2)
  fmt.Println(str)
  fmt.Print(reflect.TypeOf(str), "\n")
}

Output

int64
1010
string

In this example, we imported three basic modules.

  1. fmt
  2. reflect
  3. strconv

Inside the main() function, we declared an int64 variable with a 10 value.

Using reflect.TypeOf() function, we can print the data type of a variable in the Go console.

The strconv.FormatInt() function converts an int64 to a string with a base 2 that returns “1010” and prints the data type of the output, which is a string, as you can see in the output.

Why strconv.Itoa() function won’t help convert the int64 variable?

The strconv.Itoa() function accepts only int32 variables; if you try to use a variable of type int64, you will get the following error.

cannot use a (variable of type int64) as type int in argument to strconv.Itoa

To avoid the error, always use the int32 variable while working with strconv.Itoa() function.

Conclusion

To convert the int32 variable to string data type, use the strconv.Itoa() function.

To convert the int64 variable to string data type, use the strconv.FormatInt() function.

That’s it for this conversation example.

Further reading

How to convert string to int64

Leave a Comment