Converting int into a string. Not as easy as you'd think!
Let's say you have a number and you want to convert it to a string. The obvious thing to do would be to try something simple.
Now, you might notice that my IDE is already warning me about this approach. Let’s run it anyway and see what happens. Interesting.
Why did this happen? It’s because this method converts our number into a rune, which is a Unicode code point, and not a decimal string as we intended. So, how can we properly convert a number to a string?
There are a couple of ways to do this. Firstly, if you’re just going to print it, you can simply print the number directly. The Go standard library will handle the conversion for you and ensure it’s displayed correctly. That’s the easiest option.
But what if you want to convert it into a string you can carry around and use elsewhere? You could try another method. This works, but it’s a slower approach and generally not considered good practice.
Let’s explore a better way. This next method also works and is really fast. But what if your number isn’t a simple integer? For example, what if it’s an int64? Let’s adjust this to handle a larger number and make the syntax explicit about what we want. At this point, you’ll notice that the strconv.Itoa
function can’t be used anymore.
So, we need a different approach. We can use strconv.FormatInt
, which takes the number and a base—typically base 10, though other bases might be useful in specific cases. Let’s run this, and it still works perfectly.
The key takeaway here is: don’t directly cast a number to a string. Instead, you should typically use the strconv package. For a simple integer, use the strconv.Itoa
function. For larger numbers like an int64 or a float, use strconv.FormatInt
as shown.
I hope this was helpful. Converting numbers to strings in Go isn’t as intuitive as it could be!