Easy Ways to Convert an Integer to a String in Go
Converting an integer to a string is common when building output, logs, identifiers, URLs, or serialized data. Go provides several standard-library options depending on whether you need a simple decimal conversion or more control over formatting.
1. strconv.Itoa()
For an int in base 10, strconv.Itoa is usually the clearest choice:
package main
import (
"fmt"
"strconv"
)
func main() {
num := 42
str := strconv.Itoa(num)
fmt.Println("String value:", str)
}Itoa is equivalent to formatting the int as a base-10 integer.
2. fmt.Sprintf()
Use fmt.Sprintf when the integer is part of a larger formatted string:
package main
import "fmt"
func main() {
num := 42
str := fmt.Sprintf("item-%d", num)
fmt.Println(str)
}For a plain integer-to-string conversion, strconv.Itoa is simpler and avoids the general formatting machinery.
3. strconv.FormatInt()
Use strconv.FormatInt when working with a specific integer width or numeric base:
package main
import (
"fmt"
"strconv"
)
func main() {
num := int64(42)
fmt.Println("Decimal:", strconv.FormatInt(num, 10))
fmt.Println("Binary:", strconv.FormatInt(num, 2))
fmt.Println("Hex:", strconv.FormatInt(num, 16))
}For unsigned integers, use strconv.FormatUint.
A Common Mistake: string(num)
This does not produce the decimal digits of an integer:
str := string(42)Integer-to-string conversion with string interprets the integer as a Unicode code point. For decimal text such as "42", use strconv.Itoa, FormatInt, or formatting functions.
Conclusion
Use strconv.Itoa for ordinary int values, strconv.FormatInt or FormatUint when you need control over the base or integer type, and fmt.Sprintf when conversion is part of broader string formatting.