Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

How to Safely Convert a String to an Integer in Go

1 min read .
How to Safely Convert a String to an Integer in Go

Numbers often arrive as strings from command-line arguments, form input, files, environment variables, or APIs. Before performing arithmetic, convert the text with Go’s strconv package and handle invalid input explicitly.

1. Use strconv.Atoi() for int

Atoi is the simplest choice when you want a base-10 int:

package main

import (
	"fmt"
	"strconv"
)

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

	fmt.Println("Number:", num)
}

Invalid input such as "12a" returns an error. Never assume external text is valid without checking it.

2. Use strconv.ParseInt() for More Control

ParseInt lets you choose the base and bit size:

num, err := strconv.ParseInt("123", 10, 64)
if err != nil {
	return err
}
fmt.Println(num)

The arguments are:

  • the input string;
  • the numeric base, such as 10, 2, or 16;
  • the bit size, usually 8, 16, 32, or 64.

ParseInt returns int64. If you need a smaller integer type, choose the corresponding bit size so overflow is detected before conversion.

For example:

value, err := strconv.ParseInt(input, 10, 32)
if err != nil {
	return err
}
number := int32(value)

Passing base 0 lets Go infer the base from prefixes such as 0x for hexadecimal, but use base 10 when the input format is explicitly decimal.

3. Use strconv.ParseUint() for Unsigned Values

num, err := strconv.ParseUint("123", 10, 64)
if err != nil {
	return err
}
fmt.Println(num)

This returns uint64 and rejects negative input.

Trim Input Only When Your Format Allows It

Parsing functions reject surrounding whitespace:

input := strings.TrimSpace(rawInput)
num, err := strconv.Atoi(input)

Trimming is appropriate for human-entered fields, but protocol or file formats may require stricter validation.

Conclusion

Use strconv.Atoi for ordinary decimal int parsing, ParseInt when you need control over base or size, and ParseUint for unsigned values. Always handle parsing errors so malformed or out-of-range input cannot silently become incorrect application data.

Related Posts

chevron-up