This post will discuss various ways to convert an int to a string in the Go language.
- strconv.Itoa()
- Using fmt.Sprintf()
- And by using strconv.FormatInt()
Let’s look at each of these methods one by one.
After using the above functions, we will use the TypeOf() method of the reflect package to show you the variable’s data type. This will show that we get a string after conversion and not another data type.
strconv.Itoa()
Itoa() method is a part of the strconv package and is widely used to convert an int to a string type.
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
i := 123
str := strconv.Itoa(i)
fmt.Println("Type of str:", reflect.TypeOf(str))
fmt.Println("Converted string is:", str)
}
Output –
Type of str: string
Converted string is: 123
The type of the variable “str” is a string which is also shown by the TypeOf() method, and the value of str is also “123”.
fmt.Sprintf()
Sprintf() function is defined under the “fmt” package and returns a formatted string based on the format specifiers. There are multiple format specifiers, but we can convert an int to a string using the %d specifier.
The below piece of code will convert an int to a string type.
str := fmt.Sprintf("%d", i)
where str is the formatted string, and i is the integer.
package main
import (
"fmt"
"reflect"
)
func main() {
i := 123
str := fmt.Sprintf("%d", i)
fmt.Println("Type of str:", reflect.TypeOf(str))
fmt.Println("Converted string is:", str)
}
Output –
Type of str: string
Converted string is: 123
strconv.FormatInt()
FormatInt() is also a part of the strconv package.
It takes two arguments –
- One is the int64 data type integer
- and other is the base using which we want to convert the first argument into a string.
We can use the below line to convert an integer to a string using the FormatInt() function –
strconv.FormatInt(int64(i), 10)
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
i := 123
str := strconv.FormatInt(int64(i), 10)
fmt.Println("Type of str:", reflect.TypeOf(str))
fmt.Println("Converted string is:", str)
}
Output –
Type of str: string
Converted string is: 123
Do you know that Itoa() internally uses the FormatInt() function with base 10? Below is the internal implementation of the Itoa() function –
// Itoa is equivalent to FormatInt(int64(i), 10).
func Itoa(i int) string {
return FormatInt(int64(i), 10)
}
We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.