go

Execute multiple switch cases


I have the following code:

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)
    }
}

If I want to execute the next case I can use fallthrough, but it won't check condition against the case. I need to check the condition: I want to continue the switch case as normal, even after it met one case.

I would like to check the next case condition also with fallthrough, is there any way I can do that?


Solution

  • Short answer: no, you cannot check subsequent case conditions using fallthrough, since fallthrough is unconditional and forces the next case to be executed. That's its purpose.


    Long answer: you can still use fallthrough: if you look closely in this case you only need to reorder your cases in a way which makes sense. Note that this is not always possible though.

    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)
    }
    

    This way you can safely use fallthrough, because since the conditions are correctly ordered you already know that if num passes one of them, then it is obviously also going to pass every subsequent condition.

    Moreover, if you actually don't want to simply fallthrough to the next case, but you want to execute another case, you can add a labeled case and use goto to jump right to it.

    switch num := 75; {
    firstCase:
        fallthrough
    case num < 50:
        fmt.Println("something something\n")
    case num < 100:
        fmt.Printf("%d is less than 100\n", num)  
        goto firstCase
    }
    

    Take a look at the Go GitHub wiki here for more information.


    By the way, if you are using a switch statement and need to force some unnatural case handling then you are probably doing the whole thing wrong: consider using another approach, like some nested if statements for example.