DEV Community

Cover image for How to convert an int type value to a string type value in Go or Golang?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to convert an int type value to a string type value in Go or Golang?

#go

Originally posted here!

To convert an int type value to a string type value, you can use the Sprint() method from the fmt standard package in Go or Golang.

The Sprint() method accepts a value of any type and returns the corresponding string type version of the value.

For example, let's say we need to convert an int type value of 9000 to its string type value. To do that we can use the Sprint() method like this,

package main

import "fmt"

func main() {
    // an `int` type value
    intNum := 9000

    // convert the `intNum` value to a `string` type value
    // using the `Sprint()` method from the `fmt` package
    strNum := fmt.Sprint(intNum)

    // log to console
    fmt.Println(strNum) // "9000"
}
Enter fullscreen mode Exit fullscreen mode

As you can see from the above code that the int type is successfully converted to its corresponding string type. Yay 🥳.

See the above code live in The Go Playground.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (3)

Collapse
 
ccoveille profile image
Christophe Colombier

Interesting, I'm either using strconv.FormatInt or fmt.Sprintf("%d", strNum), never thought about fmt.Sprint.

I'm not even sure I knew it exited, thanks.

Collapse
 
melvin2016 profile image
MELVIN GEORGE

Glad it helped 😃. Christophe.

Collapse
 
thedenisnikulin profile image
Denis • Edited

You'd better use strconv.Itoa or strconv.FormatInt because fmt.Sprint* makes unnecessary allocations and uses reflection