How to convert from integer to string data type in Go
Overview
We can’t perform operations like 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 mainimport ("fmt""strconv")func main() {i := 10fmt.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
intvalue (original value + 2). -
In line 11, we pass the
intvalue we want to convert.
s2 := strconv.Itoa(i)
- In line 12, we print the
stringvalue which returns from the function concatenated with “2”.