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"
}
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 😃!
Top comments (3)
Interesting, I'm either using
strconv.FormatInt
orfmt.Sprintf("%d", strNum)
, never thought aboutfmt.Sprint
.I'm not even sure I knew it exited, thanks.
Glad it helped 😃. Christophe.
You'd better use
strconv.Itoa
orstrconv.FormatInt
becausefmt.Sprint*
makes unnecessary allocations and uses reflection