How to convert from integer to string data type in Go

Overview

We can’t perform operations like concatenationConcatenation is the operation of joining character strings end-to-end or finding substrings on integers. In order to perform these operations, we need to convert our int values to string.

We can convert an int value to a string data type using the strconv.Itao(int) method.

Syntax

strconv.Itao(int)

Parameter

strconv.Itao(int) receives an int value as a parameter.

strconv.Itao(int) returns a string value.

Code

package main
import (
"fmt"
"strconv"
)
func main() {
i := 10
fmt.Println(i + 2)
s2 := strconv.Itoa(i)
fmt.Println(s2 + "2")
}

Explanation

In the example above:

  • In lines 3-6, we import the packages that support this operation.
import (
    "fmt"
    "strconv"
)

Then,

  • In line 10, we print the int value (original value + 2).

  • In line 11, we pass the int value we want to convert.

s2 := strconv.Itoa(i)    
  • In line 12, we print the string value which returns from the function concatenated with “2”.

Free Resources