Golang Itoa: How to use strconv.Itoa() Function

Go provides built-in support to execute conversions to and from string expressions of basic data types using the strconv Package. The most familiar numeric conversions are converting string to int using Atoi() and int to string using Itoa() function in Go. Let’s see the Itoa() function and how to use it.

Golang Itoa

The strconv.Itoa() is a built-in Golang function that returns the string representation of the input value when the base is 10. The Itoa() function accepts an integer as an argument and returns a string representation of the argument.

The strconv.Itoa() function is to similar to FormatInt(int64(i), 10). The strconv.Itoa() function returns the string representation of input when the base is 10. 

To convert integers to ascii strings in Go, use the strconv.Itoa() function.

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

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

In this example, we imported two packages.

  1. fmt
  2. strconv

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.

Using a negative integer as an argument

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.

Conclusion

The itoa() function in the strconv package of the golang standard library provides a simple way to convert an int to a string. That’s it.

Further reading

Golang int64 to string

Golang string to int64

Golang ascii to rune

Leave a Comment