How to Convert Int to String in Go

Use the `strconv.Itoa()` function for standard integer-to-string conversion, or `fmt.Sprintf()` if you need more formatting control.

Use the strconv.Itoa() function for standard integer-to-string conversion, or fmt.Sprintf() if you need more formatting control. Both are built into the standard library and handle the conversion efficiently without external dependencies.

For simple conversions where you just need the decimal representation, strconv.Itoa() is the most direct and performant choice. It takes an int and returns a string.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	num := 42
	s := strconv.Itoa(num)
	fmt.Println(s) // Output: 42
}

If you need to convert integers in different bases (like binary, octal, or hexadecimal) or want to include formatting (such as padding or specific prefixes), fmt.Sprintf() is more flexible. It uses format verbs similar to C's printf.

package main

import "fmt"

func main() {
	num := 255

	// Decimal
	s1 := fmt.Sprintf("%d", num)
	
	// Hexadecimal with 0x prefix
	s2 := fmt.Sprintf("%#x", num)
	
	// Binary
	s3 := fmt.Sprintf("%b", num)

	fmt.Println(s1, s2, s3) // Output: 255 0xff 11111111
}

For negative numbers, strconv.Itoa() handles the sign automatically, producing a string with a leading minus sign. If you are working with int64 or int32 specifically, you can use strconv.FormatInt() which allows you to specify the base explicitly, offering a middle ground between the simplicity of Itoa and the verbosity of Sprintf.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	val := int64(-100)
	// Convert to binary string
	binaryStr := strconv.FormatInt(val, 2)
	fmt.Println(binaryStr) // Output: -1100100
}

Avoid using fmt.Sprint() for simple conversions if performance is critical in tight loops, as it involves more overhead than strconv.Itoa(). However, for general application logic where readability matters more than micro-optimization, fmt.Sprint() is perfectly acceptable and often preferred for its consistency with other formatting tasks.

Choose strconv.Itoa() for the fastest, cleanest conversion of standard integers, and reach for fmt.Sprintf() or strconv.FormatInt() when you need specific base representations or formatting rules.