How to Convert Int to String in Golang

Here are three ways to convert an integer to a string in Go.

  1. Using strconv.Itoa()
  2. Using strconv.FormatInt()
  3. Using strconv.Sprintf()

Convert Int to String in Golang

Method 1: Using Itoa() function

The “strconv.Itoa()” function returns the string representation of input when integer base 10 value.

Using Itoa() function

Syntax

func Itoa(i int) string

Example

package main

import (
  "fmt"
  "strconv"
)

func main() {
  data := 21
  s := strconv.Itoa(data)
  fmt.Printf("%T, %v\n", s, s)
}

Output

string, 21

Method 2: Using FormatInt() function

The strconv.FormatInt() function returns the string representation of i in the given base for 2 <= base <= 36. The result uses the lowercase letters ‘a’ to ‘z’ for digit values >= 10.

Using Itoa() function

Syntax

func FormatInt(i int64, base int) string

Example

package main

import (
 "fmt"
 "strconv"
)

func main() {
 data := int64(-19)

 str10 := strconv.FormatInt(data, 10)
 fmt.Printf("%T, %v\n", str10, str10)

 str16 := strconv.FormatInt(data, 16)
 fmt.Printf("%T, %v\n", str16, str16)
}

Output

string, -19
string, -13

Method 3: Using Sprintf() function

The fmt.Sprintf() function accepts the format and string and returns the formatted string.

Using Sprintf() function

Syntax

func Sprintf(format string, a ...interface{}) string

Example

package main

import (
 "fmt"
 "io"
 "os"
)

func main() {
 data := 19
 str := fmt.Sprintf("%v \n", data)
 io.WriteString(os.Stdout, str)
}

Output

19

Conclusion

For performance-sensitive applications, strconv.Itoa() and strconv.FormatInt() functions are generally faster and more efficient than fmt.Sprintf() function. This is because fmt.Sprintf() function parses the format string and is designed to handle various types and formatting options, which adds overhead.

In summary, if performance is a key concern and you’re doing straightforward integer-to-string conversions, you may want to stick with strconv.Itoa() or strconv.FormatInt().

Related posts

int64 to String in Go

String to Int in Go

Byte Array to String in Go