Check if string is int

You can use govalidator.

Code

govalidator.IsInt("123")  // true


Full Example

package main

import (
    "fmt"
    valid "github.com/asaskevich/govalidator"
)

func main() {
    fmt.Println("Is it a Integer? ", valid.IsInt("978"))
}

Output:

$ go run intcheck.go
Is it a Integer?  true

You can use unicode.IsDigit():

import "unicode"

func isInt(s string) bool {
    for _, c := range s {
        if !unicode.IsDigit(c) {
            return false
        }
    }
    return true
}

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.


this is better, you can check for ints upto 64 ( or less ) bits

strconv.Atoi only supports 32 bits

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

try it out with v := "12345678900123456789"

Tags:

Go