In this blog, we will take a look at conversion in golang, primarily how to convert int to string in Golang.
Let’s First understand the typical behaviour of Golang String Literal.
Golang Rune
Rune Data type in Golang is an alias for int32. It is primarily used to store utf8 characters.
A String in Golang is a collection of rune.
func main() {
s := 'A'
fmt.Printf("%T, %v",s,s)
}
Output:
int32, 65
The Variable ‘s’ stores a character, but when printed the type and value of the variable ‘s’, the output is int32 type and value of 65 (Capital ‘A’ ASCII Value).
In Order to Convert it into string, the rune type to be type casted to string.
Example:
func main() {
s := 'A'
fmt.Printf("%T, %v",string(s),string(s))
}
output:
string, A
Convert Int to String in Golang
Lets see how the conversion from Golang Int to String works when we use the plain conversion as above:
s := 65
fmt.Printf("%T, %v", string(s), string(s))
Output:
string, A
The Value we wanted was “65” in String, but the 65 was Converted to ASCII value i.e A.
Let’s look how we can convert int to string, but not to its ASCII Corresponding value.
Golang Strconv Itoa
The Golang Strconv Itoa Function takes an integer value and converts it to string and returns it.
package main
import (
"fmt"
"strconv"
)
func main() {
i := 65
s := strconv.Itoa(i)
fmt.Printf("%T, %v\n", s, s)
}
Output:
string, 65
This time the int is converted to string, but not to its ASCII Corresponding value.
Another way to implement conversion from int to string is using the FormatInt() function in Golang strconv package.
Golang int to string using FormatInt
func FormatInt(i int64, base int) string
The Go strconv FormatInt function takes an integer value and the base and returns the string converted integer value.
Base 10 is for Decimal number, Base 2 for binary, Base 8 for octal and Base 18 for hexadecimal value.
n := int64(42)
var s string
s = strconv.FormatInt(n, 10)
fmt.Printf("%T, %v\n", s, s)
s = strconv.FormatInt(9, 2)
fmt.Printf("%T, %v\n", s, s)
s = strconv.FormatInt(n, 16)
fmt.Printf("%T, %v\n", s, s)
Output:
string, 42
string, 1001
string, 2a
Learn more about Golang strconv package from the official Documentation.