Gaaker Go

Golang Switch without a condition

The second form of the switch statement is to not provide any value to be judged, and then test different conditions in each case branch.

When the test result of any branch is true, the code of that branch will be executed.

This looks a lot like a chained if/else statement, but it is more readable than the former.

The following is a complete code example.

package main

func main() {
    var num1 int = 7

    switch {
    case num1 <0:
        println("Number is negative")
    case num1> 0 && num1 <10:
        println("Number is between 0 and 10")
        println("Number is 10 or greater")

Below is the program output:

Number is between 0 and 10
< Switch without a condition Switch without a condition >