patterngoCritical
Check if string is int
Viewed 0 times
stringcheckint
Problem
How can I check if a string value is an integer or not in Go?
Something like
Note: I know that
The problem with
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"Solution
As you said, you can use strconv.Atoi for this.
You could use
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.Code Snippets
if _, err := strconv.Atoi(v); err == nil {
fmt.Printf("%q looks like a number.\n", v)
}Context
Stack Overflow Q#22593259, score: 211
Revisions (0)
No revisions yet.