4 ways to convert int to string in Go

Go: int to string conversion

Integer to string conversion is a type conversion or type casting, where an entity of integer data type is changed into string one.

In Golang, we can do the int to string conversion with the strconv.FormatInt, strconv.Itoa, or fmt.Sprintf functions.

Go: int to string conversion using strconv.Itoa() function:

An integer can be converted to a string in Golang using the Itoa function within the strconv library. This library supports conversions to and from string representations to various other data types.

    package main

    import (
        "fmt"
        "strconv"
    )

    func main() {
        i := 42
        s := strconv.Itoa(i)
        fmt.Printf("type of s: %T, s: %s\n", s, s)
    }

Output:

    type of s: string, s: 42

Go: int to string conversion using fmt.Sprintf() function:

fmt.Sprintf function formats according to a format specifier and returns the resulting string.

    package main

    import (
        "fmt"
    )

    func main() {
        i := 42
        s := fmt.Sprintf("%d", i)
        fmt.Printf("type of s: %T, s: %s\n", s, s)
    }

Output:

    type of s: string, s: 42

Go: int to string conversion using strconv.FormatInt() function:

The strconv.FormatInt returns the string representation of a value in the given base; where for 2 <= base <= 36.

    package main

    import (
        "fmt"
        "strconv"
    )

    func main() {
        i := int64(42)
        s := strconv.FormatInt(i, 10)
        fmt.Printf("type of s: %T, s: %s\n", s, s)
    }

Output:

    type of s: string, s: 42

Go: int to string conversion using string conversion (string()):

This approach is not recommended as it does not convert the integer to string correctly. It only converts the integer to a rune (a Unicode code point).

    package main

    import (
        "fmt"
    )

    func main() {
        i := 42
        s := string(i)
        fmt.Printf("type of s: %T, s: %s\n", s, s)
    }

Output:

    type of s: string, s: *