Ad Space — Top Banner

strconv: parsing error

Go Runtime Error

Severity: Moderate

What Does This Error Mean?

A Go strconv parsing error occurs when you try to convert a string to a number but the string does not contain a valid number. For example, strconv.Atoi called with abc returns this error. Always check the error return value before using the converted result.

Affected Models

  • Go 1.x (all versions)
  • strconv.Atoi
  • strconv.ParseInt
  • strconv.ParseFloat
  • strconv.ParseBool

Common Causes

  • Input string contains non-numeric characters
  • Empty string passed to a numeric conversion function
  • String contains leading or trailing spaces
  • Number too large for the target type — overflow
  • Wrong base specified for integer parsing (e.g. binary string parsed as decimal)

How to Fix It

  1. Always check the error return from strconv functions before using the result.

    Every strconv function returns (value, error). Never ignore the error. Example: n, err := strconv.Atoi(s); if err != nil { log.Fatal(err) }

  2. Trim whitespace from the input string before parsing.

    Use strings.TrimSpace(s) before passing to strconv. Leading or trailing spaces cause parsing to fail even when the number itself is valid.

  3. Validate the input string before attempting conversion.

    For user input or external data, check the format first before passing to strconv. A regex or length check prevents obvious failures.

  4. For user-facing errors, provide a clear message rather than panicking.

    Do not call log.Fatal on parse errors from user input — return a helpful error message instead. Only fatal on data that should always be valid, like config files under your control.

Frequently Asked Questions

What is the difference between strconv.Atoi and strconv.ParseInt in Go?

strconv.Atoi is shorthand for ParseInt with base 10 and a bit size matching int. Use Atoi for simple integer conversion. Use ParseInt when you need a specific bit size (int32, int64) or a non-decimal base.

How do I convert a string to an int safely in Go?

Use: n, err := strconv.Atoi(strings.TrimSpace(s)) Always check err before using n. If err is not nil, the string was not a valid integer — handle the error appropriately for your use case.