based on user input from command line, switch case returns rating for an integer. Since command line arguments are of type string, I first convert it to int and then use it in switch.
package main
import (
"fmt"
"os"
"reflect"
"strconv"
)
func main() {
rating, _ := strconv.Atoi(os.Args[1])
fmt.Println(reflect.TypeOf(rating))
switch rating {
case rating >= 2100:
fmt.Println("grand master")
case rating >= 1900:
fmt.Println("candidate master")
case rating >= 1600:
fmt.Println("expert")
case rating >= 1400:
fmt.Println("pupil")
case rating < 1400:
fmt.Println("newbie")
}
}
Now there is error on rating >= 2100, for all comparisons rather. It goes as follows:
cannot convert rating >= 2100 (untyped bool value) to intcompilerInvalidUntypedConversion
Not able to understand how to resolve this.
Please help!
If you use a switch expression, you have to use case expressions where they are comparable. Spec: Switch statements:
For each (possibly converted) case expression
xand the valuetof the switch expression,x == tmust be a valid comparison.
That is, if you use switch rating { ... }, then you only need to specify the integer values, e.g. 2100, and not a comparison like rating >= 2100.
Obviously you don't want single values but ranges, so omit the switch expression:
switch {
case rating >= 2100:
fmt.Println("grand master")
case rating >= 1900:
fmt.Println("candidate master")
case rating >= 1600:
fmt.Println("expert")
case rating >= 1400:
fmt.Println("pupil")
case rating < 1400:
fmt.Println("newbie")
}