Home

Converting Integers to Strings in Go: Methods and Examples

24 views

In Go, converting an integer to a string is a common task, and there are several ways to achieve it. The standard library provides a few different methods for this purpose, each with its own use cases and advantages. Here are the primary methods:

1. Using fmt.Sprintf

The fmt.Sprintf function formats according to a format specifier and returns the resulting string. This is a very flexible and straightforward way to convert an integer to a string.

package main

import (
    "fmt"
)

func main() {
    x := 123
    str := fmt.Sprintf("%d", x)
    fmt.Println(str) // Output: "123"
}

2. Using strconv.Itoa

The strconv package provides a function Itoa (integer to ASCII) that converts an integer to a decimal string.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    x := 123
    str := strconv.Itoa(x)
    fmt.Println(str) // Output: "123"
}

3. Using strconv.FormatInt

If you need to convert an integer in a different base (binary, octal, hexadecimal, etc.), you can use the strconv.FormatInt function. It takes the integer, the base, and returns the formatted string.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    x := int64(123)
    str := strconv.FormatInt(x, 10)
    fmt.Println(str) // Output: "123"
    
    // For other bases
    binaryStr := strconv.FormatInt(x, 2)
    fmt.Println(binaryStr) // Output: "1111011" (binary representation)
    
    hexStr := strconv.FormatInt(x, 16)
    fmt.Println(hexStr) // Output: "7b" (hexadecimal representation)
}

4. Using strconv.FormatUint

If you are working with unsigned integers (uint or uint64), you can use strconv.FormatUint to convert the unsigned integer to a string.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    x := uint64(123)
    str := strconv.FormatUint(x, 10)
    fmt.Println(str) // Output: "123"
}

Summary

  • fmt.Sprintf: Flexible and handles different data types and formatting options.
  • strconv.Itoa: Simple and straightforward for converting int to string in base 10.
  • strconv.FormatInt: Useful for converting int to string in various bases (binary, octal, hex, etc.).
  • strconv.FormatUint: Similar to FormatInt, but for unsigned integers.

Each method has its own advantages, so choose the one that best fits your needs. These methods ensure that you can easily and efficiently convert integers to strings in Go.