How to Fix strconv.atoi: parsing “”: invalid syntax in Golang

Strconv.atoi: parsing “”: invalid syntax error typically occurs in Go when the “strconv.Atoi() function is called with an empty string as an argument.”

Reproduce the error

package main

import (
  "fmt"
  "strconv"
)

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

Output

Error: strconv.Atoi: parsing "": invalid syntax

How to fix the error

To fix this error, you can “add a check before calling strconv.Atoi() to ensure that the string is not empty and possibly contains a valid integer representation.”

package main

import (
  "fmt"
  "strconv"
)

func main() {
  s := ""
  if s != "" {
    n, err := strconv.Atoi(s)
    if err != nil {
      fmt.Println("Error:", err)
    } else {
      fmt.Println("Converted value:", n)
    }
  } else {
    fmt.Println("String is empty, cannot convert.")
  }
}

Output

String is empty, cannot convert.

This way, you can handle the empty string case separately and avoid triggering the error from strconv.Atoi().

That’s it!