0
0
GoHow-ToBeginner · 2 min read

Go: How to Convert int to string Easily

In Go, convert an int to a string using strconv.Itoa(yourInt) which returns the string form of the integer.
📋

Examples

Input123
Output"123"
Input0
Output"0"
Input-456
Output"-456"
🧠

How to Think About It

To convert an int to a string in Go, think of turning a number into readable text. You use a built-in function that takes the number and returns its text form, so you can print or use it as words.
📐

Algorithm

1
Import the strconv package.
2
Call the function that converts int to string with your integer as input.
3
Store or use the returned string value.
💻

Code

go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	num := 123
	str := strconv.Itoa(num)
	fmt.Println(str)
}
Output
123
🔍

Dry Run

Let's trace converting the integer 123 to a string.

1

Start with integer

num = 123

2

Convert using strconv.Itoa

str = strconv.Itoa(123) -> "123"

3

Print the string

Output: 123

StepValue
1num = 123
2str = "123"
3print str -> 123
💡

Why This Works

Step 1: Import strconv package

The strconv package provides functions to convert between strings and other types.

Step 2: Use strconv.Itoa

Itoa means integer to ASCII (string), it converts the int to its string form.

Step 3: Print the string

The converted string can be printed or used wherever a string is needed.

🔄

Alternative Approaches

Using fmt.Sprintf
go
package main

import (
	"fmt"
)

func main() {
	num := 123
	str := fmt.Sprintf("%d", num)
	fmt.Println(str)
}
This method formats the int as a string but is slightly slower than strconv.Itoa.
Using strconv.FormatInt for int64
go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	var num int64 = 123
	str := strconv.FormatInt(num, 10)
	fmt.Println(str)
}
Use this when working with int64 types; it converts the number to base 10 string.

Complexity: O(n) time, O(n) space

Time Complexity

The time depends on the number of digits in the integer, so it is O(n) where n is digit count.

Space Complexity

The space needed is proportional to the length of the string created, also O(n).

Which Approach is Fastest?

strconv.Itoa is faster and more direct than fmt.Sprintf, which does formatting and is more flexible but slower.

ApproachTimeSpaceBest For
strconv.ItoaO(n)O(n)Simple int to string conversion
fmt.SprintfO(n)O(n)Formatted string output with more control
strconv.FormatIntO(n)O(n)Converting int64 to string with base control
💡
Use strconv.Itoa for simple int to string conversion because it's fast and clear.
⚠️
Trying to convert int to string by casting like string(num) which converts to a character, not the number's text.