What is the strconv.Itoa() Function in Golang

The strconv.Itoa() function in Golang is equivalent to the FormatInt(int64(i), 10) function that “returns the string representation of the input value when the base is 10”. The function accepts an integer as an argument and returns a string representation of the argument.

Syntax

func Itoa(i int) string

Arguments

The Itoa() function takes an input i of type integer.

Return Value

The strconv.Itoa() function returns a string that represents i.

Example 1

package main

import (
  "fmt"
  "strconv"
)

func main() {
  str1 := strconv.Itoa(19)
  fmt.Printf("%T, %v\n", str1, str1)

  str2 := strconv.Itoa(21)
  fmt.Printf("%T, %v\n", str2, str2)
}

Output

string, 19
string, 21

The fmt package provides I/O functions like Printf() that print the output on the console.

To get the data type of a variable in Go, use the %T inside the Printf() function, which prints the variable’s data type.

The strconv.Itoa() function converts an integer to a string, and we print its data type, a string.

Example 2

Let’s take a negative integer as an input to the strconv.Itoa() function.

package main

import (
 "fmt"
 "strconv"
)

func main() {
 int1 := -19
 fmt.Printf("Output: %d \n", int1)
 fmt.Printf("Data Type: %T \n", int1)
 fmt.Println("After conversion:")
 str1 := strconv.Itoa(int1)
 fmt.Printf("Output: %v \n", str1)
 fmt.Printf("Output: %T \n", str1)
}

Output

Output: -19
Data Type: int
After conversion:
Output: -19
Output: string

We assigned a negative integer value to a variable and printed its value and data type in this example.

We are then using strconv.Itoa() method, we converted from integer to string and printed its value and data type, which is a string.

That’s it.

Leave a Comment