Golang int64 to string conversion

Sometimes we have to convert int64 to string in Golang. We can use different functions to achieve this.

Using strconv.Itoa() to convert Golang int64 to string

Golang strconv.Itoa() function can be used to convert int64 to string. Let’s have a look at a simple example.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	s := strconv.Itoa(97)
	fmt.Println(s)
}

Output: 97

Why not use string() to convert int64 to string?

If you are wondering why can’t we use string() function to pass int argument and create a string object, let’s see what happens when we try that.

s := string(97)
fmt.Println(s)  // prints "a"

The string() function treats integer argument as a code point value for the string and returns the corresponding string. So, rather than getting a string with value “97”, we are getting “a” because its Unicode code point value is 97.

Convert int64 to string with base

What if we want the string representation in some other base. Don’t worry, strconv package has a FormatInt() function for this kind of conversion.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var a int64 = 28
	var b int64 = 4
	
	fmt.Println(strconv.FormatInt(a, 16)) // prints "1c"
	fmt.Println(strconv.FormatInt(b, 2)) //  prints "100"
}

How about converting int8 or int32 to string?

The Itoa() and FormatInt() functions work on int64 only. So, if you have to convert any different integer types to string, use the int() function to first convert them to int64 format.

var a int32 = 28
fmt.Println(strconv.Itoa(a)) 
// error "cannot use a (type int32) as type int in argument to strconv.Itoa"

The correct way of conversion is:

a := int8(28)
x := int(a)
	
fmt.Println(strconv.Itoa(x)) // prints "28"

Conclusion

If you have to convert int64 to string, use strconv.Itoa() function. If you want the string representation in different base, use FormatInt() function.

Reference: strconv package