0
0
GoHow-ToBeginner · 2 min read

Go: How to Convert String to Int Easily

In Go, convert a string to an int using strconv.Atoi(stringValue), which returns the integer and an error.
📋

Examples

Input"123"
Output123
Input"0"
Output0
Input"-45"
Output-45
🧠

How to Think About It

To convert a string to an int in Go, you use the strconv.Atoi function which tries to read the string as a number. If the string contains only digits (and an optional sign), it returns the number and no error. Otherwise, it returns an error you can check.
📐

Algorithm

1
Get the input string.
2
Use strconv.Atoi to try converting the string to an integer.
3
Check if an error occurred during conversion.
4
If no error, return the integer value.
5
If error, handle it (e.g., print a message or use a default).
💻

Code

go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "123"
	num, err := strconv.Atoi(str)
	if err != nil {
		fmt.Println("Conversion error:", err)
		return
	}
	fmt.Println(num)
}
Output
123
🔍

Dry Run

Let's trace converting the string "123" to int using strconv.Atoi.

1

Input string

str = "123"

2

Call strconv.Atoi

num, err = strconv.Atoi("123")

3

Check error

err is nil, so conversion succeeded

4

Print result

Output: 123

StepActionValue
1Input string"123"
2Call strconv.Atoinum=123, err=nil
3Check errorerr=nil (no error)
4Print result123
💡

Why This Works

Step 1: Use strconv.Atoi

The strconv.Atoi function reads the string and tries to convert it to an integer.

Step 2: Handle errors

If the string is not a valid number, strconv.Atoi returns an error which you should check.

Step 3: Use the integer

If no error, you can safely use the returned integer value in your program.

🔄

Alternative Approaches

Using strconv.ParseInt
go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "123"
	num64, err := strconv.ParseInt(str, 10, 0)
	if err != nil {
		fmt.Println("Conversion error:", err)
		return
	}
	fmt.Println(int(num64))
}
ParseInt allows specifying base and bit size, useful for more control but requires casting to int.

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

Time Complexity

The function scans each character of the string once, so time grows linearly with string length.

Space Complexity

Uses constant extra space for the integer and error values.

Which Approach is Fastest?

Both strconv.Atoi and strconv.ParseInt have similar performance; Atoi is simpler for base 10 integers.

ApproachTimeSpaceBest For
strconv.AtoiO(n)O(1)Simple base-10 string to int conversion
strconv.ParseIntO(n)O(1)Conversion with base and bit size control
💡
Always check the error returned by strconv.Atoi to avoid crashes on invalid input.
⚠️
Ignoring the error returned by strconv.Atoi and assuming conversion always succeeds.