英文:
How do I get the switch statement to work when there is an error in switch case
问题
根据用户从命令行输入的内容,switch case 语句根据一个整数返回评级。由于命令行参数的类型是字符串,我首先将其转换为 int
,然后在 switch 语句中使用。
package main
import (
"fmt"
"os"
"reflect"
"strconv"
)
func main() {
rating, _ := strconv.Atoi(os.Args[1])
fmt.Println(reflect.TypeOf(rating))
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")
}
}
现在在 rating >= 2100
和其他所有比较中都存在错误。错误信息如下:
cannot convert rating >= 2100 (untyped bool value) to intcompilerInvalidUntypedConversion
我无法理解如何解决这个问题。
请帮忙解决!
英文:
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!
答案1
得分: 6
如果你使用switch
表达式,你必须在可比较的地方使用case
表达式。规范:Switch语句:
对于每个(可能转换的)case表达式
x
和switch表达式的值t
,x == t
必须是一个有效的比较。
也就是说,如果你使用switch rating { ... }
,那么你只需要指定整数值,例如2100
,而不是像rating >= 2100
这样的比较。
显然,你不想要单个值,而是范围,所以省略switch表达式:
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")
}
英文:
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 x
and the value t
of the switch expression, x == t
must 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")
}
答案2
得分: 0
你只是在重复已经存在于上方的变量名。
英文:
you're basically repeating the variable name that already exists aboveenter image description here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论