In Golang, to convert int
to string
you can use strconv.Itoa(i)
and strconv.FormatInt(i, base)
. Lets walk through this tutorial to see the examples in practice
Convert int to string with strconv.Itoa(i)
- You can use
strconv.Itoa(i)
to convert an integeri
to string.Itoa
stands for integer to ASCII
package main
import (
"fmt"
"strconv"
)
func main() {
i := 1
s := strconv.Itoa(i)
fmt.Println(s)
}
Output
1
- The input parameter must be a 32 bit integer, otherwise you would get the compile error
package main
import (
"fmt"
"strconv"
)
func main() {
var i int64 = 1
s := strconv.Itoa(i) // compile error
fmt.Println(s)
}
Output
cannot use i (type int64) as type int in argument to strconv.Itoa
Convert int to string with strconv.FormatInt(i, base)
The strconv.FormatInt(i, base)
convert the given 64 bit integer i
to string in the given base (2 to 36)
Itoa(i)
is equivalent to FormatInt(int64(i), 10)
Output
1001