How to convert int to string in Go?

How can you create a string from an int in Golang? There are several ways to do so.

Using strconv

As the standard library for string work, this is the one that you will use the most. First of all, let us do an import of the Library in our code.

import (
	...
	"strconv"
)

Go has several integer types: uint8, uint16, uint32, uint64, int8, int16, int32 and int64. But strconv only support 3 of them which is int, int64 and uint64. So let's see how to use it.

Parse string to int

func main() {
	res, err := strconv.Atoi("10")
	if err != nil {
		fmt.Printf("%s\n", err)
	}
	fmt.Printf("%d\n", res+10)
}

Parse string to int64

func main() {
	res, err := strconv.ParseInt("10001", 10, 64)
	if err != nil {
		fmt.Printf("%s\n", err)
	}
	fmt.Printf("%d\n", res)
}

Parse string to uint64

func main() {
	res, err := strconv.ParseUint("10002", 10, 64)
	if err != nil {
		fmt.Printf("%s\n", err)
	}
	fmt.Printf("%d\n", res)
}

If you need other types you can just cast it this way.

res, err := strconv.ParseInt("10001", 10, 64)
if err != nil {
    ...
}
int8(str)