go

Convert Int To String in Golang | Itoa and FormatInt

divshekhar

Divyanshu Shekhar

Posted on September 27, 2020

Convert Int To String in Golang | Itoa and FormatInt

Golang Rune

Rune Data type in Golang is an alias for int32. It is primarily used to store utf8 characters.

A String in Golang is a collection of rune.

func main() {
    s := 'A'
    fmt.Printf("%T, %v",s,s)

}
Output:

int32, 65
Enter fullscreen mode Exit fullscreen mode

The Variable ‘s’ stores a character, but when printed the type and value of the variable ‘s’, the output is int32 type and value of 65 (Capital ‘A’ ASCII Value).

In Order to Convert it into string, the rune type to be type casted to string.

Example:

func main() {
    s := 'A'
    fmt.Printf("%T, %v",string(s),string(s))

}
output:

string, A
Enter fullscreen mode Exit fullscreen mode

Convert Int to String in Golang

Lets see how the conversion from Golang Int to String works when we use the plain conversion as above:

s := 65
fmt.Printf("%T, %v", string(s), string(s))
Output:

string, A
Enter fullscreen mode Exit fullscreen mode

The Value we wanted was “65” in String, but the 65 was Converted to ASCII value i.e A.

Let’s look how we can convert int to string, but not to its ASCII Corresponding value.

Golang Strconv Itoa

The Golang Strconv Itoa Function takes an integer value and converts it to string and returns it.
Learn about Golang Strconv Iota and FormatInt from the original post.

💖 💪 🙅 🚩
divshekhar
Divyanshu Shekhar

Posted on September 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related