How to Convert int64 to String in Golang

To convert int64 to string in Golang, you can use the “strconv.Itoa()” function. The function returns a string representation of a given integer.

Example 1: Using strconv.Itoa() function

package main

import (
  "fmt"
  "strconv"
)

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

Output

99

Example 2: Convert int64 to string with base

To get the string representation from int64 in another base in Go, you can use the “strconv.FormatInt()” function.

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

That’s all!

Leave a Comment