How to Convert String to Int in Go

Use `strconv.Atoi` for simple base-10 conversion or `strconv.ParseInt` when you need to specify the bit size or handle different bases.

Use strconv.Atoi for simple base-10 conversion or strconv.ParseInt when you need to specify the bit size or handle different bases. Both functions return an integer and an error, so you must check the error to handle invalid input gracefully.

For most standard cases where you expect a base-10 integer, strconv.Atoi is the idiomatic choice because it returns an int directly. If you need to parse a specific bit size (like int64) or a non-decimal base, use strconv.ParseInt.

Here is a practical example using strconv.Atoi for a command-line argument:

package main

import (
	"fmt"
	"os"
	"strconv"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Usage: go run main.go <number>")
		return
	}

	// Convert string to int
	val, err := strconv.Atoi(os.Args[1])
	if err != nil {
		fmt.Printf("Invalid number: %v\n", err)
		return
	}

	fmt.Printf("Converted value: %d\n", val)
}

If you need to parse a large number or a specific base (like hexadecimal), use strconv.ParseInt. The second argument is the base (0 for auto-detect, 10 for decimal, 16 for hex), and the third is the bit size.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// Parse a hex string into an int64
	hexStr := "1A"
	val, err := strconv.ParseInt(hexStr, 16, 64)
	if err != nil {
		fmt.Printf("Parse error: %v\n", err)
		return
	}

	fmt.Printf("Hex %s as int64: %d\n", hexStr, val)

	// Parse a large decimal string
	largeStr := "9223372036854775807"
	bigVal, err := strconv.ParseInt(largeStr, 10, 64)
	if err != nil {
		fmt.Printf("Overflow or invalid: %v\n", err)
	} else {
		fmt.Printf("Large int: %d\n", bigVal)
	}
}

Always check the error returned by these functions. If the string contains non-numeric characters or exceeds the range of the target integer type, the conversion will fail and return a non-nil error. Never ignore this error in production code, as it can lead to unexpected zero values or logic bugs.