How to Convert Golang Int to String
Golang has a built-in package called strconv that provides functions that convert int to string. I have already covered how to convert string to int in this blog. Feel free to check it out.
Golang int to string
To convert Golang int to string, use the strconv.FormatInt() or strconv.Itoa() function. The FormatInt() function returns a string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters ‘a’ to ‘z’ for digit values >= 10.
The strconv.Itoa() is is shorthand for FormatInt(int64(i), 10).
Golang int/int64 to string
Go (Golang) provides string and integer conversion directly from a package coming from the standard library strconv.
To convert an integer value to a string in Golang, we can use the FormatInt function from the strconv package.
func FormatInt(i int64, base int) string
Golang FormatInt() function returns the string representation of i in the given base, for 2 <= base <= 36. The final result uses the lower-case letters ‘a’ to ‘z’ for digit values >= 10.
Example
// hello.go package main import ( "fmt" "reflect" "strconv" ) func main() { info := 1121 /** converting the info variable into a string using FormatInt method */ str2 := strconv.FormatInt(int64(info), 10) fmt.Println(str2) fmt.Println(reflect.TypeOf(str2)) }
Output
go run hello.go 1121 string
We have used the reflect package to use the Typeof() method to determine the data type, and it is a string. In addition, Golang reflects that the package has methods for inspecting the type of variables. Then we have converted Golang int to string using FormatInt() method.
func Itoa(i int) string
Golang strconv.Itoa() is equivalent to FormatInt(int64(i), 10).
Let’s see the example of how we can use these functions to convert an integer to an ASCII string.
// hello.go package main import ( "fmt" "reflect" "strconv" ) func main() { info := 1121 fmt.Println(reflect.TypeOf(info)) /** converting the info variable into a string using FormatInt method */ str2 := strconv.Itoa(info) fmt.Println(str2) fmt.Println(reflect.TypeOf(str2)) }
Output
go run hello.go int 1121 string
In a plain conversion, the value is interpreted as the Unicode code point, and the resulting string will contain a character represented by that code point encoded in UTF-8.
See the following code.
package main import ( "fmt" "reflect" ) func main() { s := 97 fmt.Println(reflect.TypeOf(s)) /** converting the info variable into a string using FormatInt method */ str2 := string(97) fmt.Println(str2) fmt.Println(reflect.TypeOf(str2)) }
Output
go run hello.go int a string
Conclusion
Golang strconv package provides FormInt() and Itoa() function to convert go integer to string, and we can verify the data type using the refect package.