Check if string is int


How can I check if a string value is an integer or not in Go?

Something like

v := "4"
if isInt(v) {
  fmt.Println("We have an int, we can safely cast this with strconv")

Note: I know that strconv.Atoi returns an error, but is there any other function to do this?

The problem with strconv.Atoi is that it will return 7 for "a7"


As you said, you can use strconv.Atoi for this.

if _, err := strconv.Atoi(v); err == nil {
    fmt.Printf("%q looks like a number.\n", v)

You could use scanner.Scanner (from text/scanner) in mode ScanInts, or use a regexp to validate the string, but Atoi is the right tool for the job.

Answered By – Paul Hankin

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.