Go 执行多个开关情况

Go 执行多个开关情况,go,Go,我有以下代码: package main import ( "fmt" ) func main() { switch num := 75; { //num is not a constant case num < 50: fmt.Printf("%d is lesser than 50\n", num) case num < 100: fmt.Printf("%d is lesser than 100\n",

我有以下代码:

package main

import (
    "fmt"
)

func main() {

    switch num := 75; { //num is not a constant
    case num < 50:
        fmt.Printf("%d is lesser than 50\n", num)   
    case num < 100:
        fmt.Printf("%d is lesser than 100\n", num)  
    case num < 60:
        fmt.Printf("%d is lesser than 60", num)
    case num < 200:
        fmt.Printf("%d is lesser than 200", num)
    }
}
主程序包
进口(
“fmt”
)
func main(){
开关编号:=75;{//num不是常数
例数<50:
fmt.Printf(“%d”小于50\n“,num)
例数<100:
fmt.Printf(“%d”小于100\n“,num)
例数<60:
fmt.Printf(“%d”小于60“,num)
例数<200:
fmt.Printf(“%d小于200”,num)
}
}
如果我想执行下一个案例,我可以使用
故障排除
,但它不会根据案例检查条件。我需要检查条件:我想继续正常开关情况,即使它遇到一个情况


我想用
fallthrough
检查下一个案例的条件,有什么办法吗?

简短回答:,您不能使用
fallthrough
检查后续的
案例
条件,因为
fallthrough
是无条件的,并强制执行下一个案例。这就是它的目的


详细回答:您仍然可以使用
故障排除法
:如果仔细查看本案例,您只需以合理的方式重新排列案例。请注意,一般情况下并非如此

switch num := 75; {
case num < 50:
    fmt.Printf("%d is less than 50\n", num)
    fallthrough // Any number less than 50 will also be less than 60
case num < 60:
    fmt.Printf("%d is less than 60\n", num)
    fallthrough // Any number less than 60 will also be less than 100
case num < 100:
    fmt.Printf("%d is less than 100\n", num)      
    fallthrough // Any number less than 100 will also be less than 200
case num < 200:
    fmt.Printf("%d is less than 200\n", num)
}
更多信息,请查看GoGithub wiki



< >强> >“<强”>,如果您使用的是“代码>开关/<代码>语句,并且需要强制一些不自然的情况处理,那么您可能正在做错误的事情:考虑使用另一种方法,例如一些嵌套的<代码>例如语句。

简短回答:<强>否<强>您不能使用

故障排除
检查后续的
案例
条件,因为
故障排除
是无条件的,并强制执行下一个案例。这就是它的目的


详细回答:您仍然可以使用
故障排除法
:如果仔细查看本案例,您只需以合理的方式重新排列案例。请注意,一般情况下并非如此

switch num := 75; {
case num < 50:
    fmt.Printf("%d is less than 50\n", num)
    fallthrough // Any number less than 50 will also be less than 60
case num < 60:
    fmt.Printf("%d is less than 60\n", num)
    fallthrough // Any number less than 60 will also be less than 100
case num < 100:
    fmt.Printf("%d is less than 100\n", num)      
    fallthrough // Any number less than 100 will also be less than 200
case num < 200:
    fmt.Printf("%d is less than 200\n", num)
}
更多信息,请查看GoGithub wiki



<>强> > ,如果您使用的是<代码>开关语句,并且需要强制一些不自然的情况处理,那么您可能做了错误的事情:考虑使用另一种方法,例如一些嵌套的<>代码>如果语句。一般的解决方案是将switch语句重写为一系列if语句。在这里重新排列用例时,一般的解决方案是将switch语句重写为一系列if语句。