Go — Parsing integers with a success flag
In Go, strconv.Atoi converts decimal text to an int and reports an error when conversion fails. A separate range check determines whether the number is a valid seat.
A simple example
Turn text into a number
- Start with "2"
- Do this Read an integer, add 1
- Result 3
package main
import "fmt"
import "strconv"
func main() {
n, err := strconv.Atoi("2")
if err == nil {
fmt.Println(n + 1)
}
}
3
Validate a seat number
The decimal-digit check excludes signed tokens. Atoi then checks conversion and range for int. The caller uses the boolean together with the returned value before printing a seat.
A minibus has seats numbered 1 to 8. A passenger entering 3 can be assigned that seat. Zero is numeric but outside the seating plan, and x cannot be read as a whole seat number.
Run the example
Go 1.20 or later. Run these commands from the directory containing the example.
go run main.go
package main
import (
"fmt"
"strconv"
)
func seatNumber(text string) (int, bool) {
for _, ch := range text {
if ch < '0' || ch > '9' {
return 0, false
}
}
n, err := strconv.Atoi(text)
return n, err == nil && n >= 1 && n <= 8
}
func main() {
for _, text := range []string{"3", "0", "x"} {
if n, ok := seatNumber(text); ok {
fmt.Println(n)
} else {
fmt.Println("invalid")
}
}
}
3 invalid invalid
Only whole-number seat labels from 1 through 8 are accepted. The text 3 passes both checks. Zero parses but is outside the range. The letter x does not represent a decimal seat number.
Try it yourself
Predict the results for 8, 9, and an empty string.
Check your answer
Only 8 is accepted. Nine is outside the range and an empty string has no digits. The existing loop can continue after either rejection.