Go language switch statement

Go language conditional statement

The switch statement is used to perform different actions based on different conditions. Each case branch is unique and is tested one by one from top to bottom until a match is found.

The switch statement executes from top to bottom until a match is found, and there is no need to add a break after the matched case.

By default, each case in switch comes with a break statement at the end, so after a successful match, other cases will not be executed. If we need to execute subsequent cases, we can usefallthrough 。

Syntax

The syntax of the switch statement in the Go programming language is as follows:

switch var1 {
    case val1:
        ...
    case val2:
        ...
    default:
        ...
}

The variable var1 can be of any type, while val1 and val2 can be any values of the same type. The type is not limited to constants or integers, but must be the same type; or expressions whose final result is of the same type.

You can test multiple values that may match at the same time, separating them with commas, for example: case val1, val2, val3.

Flowchart:

Example

package main

import "fmt"

func main() {
   /* Define local variables */
   var grade string = "B"
   var marks int = 90

   switch marks {
      case 90: grade = "A"
      case 80: grade = "B"
      case 50,60,70 : grade = "C"
      default: grade = "D"  
   }

   switch {
      case grade == "A" :
         fmt.Printf("Excellent!\n" )    
      case grade == "B", grade == "C" :
         fmt.Printf("Good\n" )      
      case grade == "D" :
         fmt.Printf("Pass\n" )      
      case grade == "F":
         fmt.Printf("Fail\n" )
      default:
         fmt.Printf("Poor\n" );
   }
   fmt.Printf("Your grade is %s\n", grade );      
}

The execution result of the above code is:

优秀!
你的等级是 A

Type Switch

The switch statement can also be used for a type-switch to determine the actual type stored in an interface variable.

Type Switch syntax format is as follows:

switch x.(type){
    case type:
       statement(s);      
    case type:
       statement(s); 
    /* 你可以定义任意个数的case */
    default: /* 可选 */
       statement(s);
}

Example

package main

import "fmt"

func main() {
   var x interface{}
     
   switch i := x.(type) {
      case nil:  
         fmt.Printf(" The type of x is %T",i)                
      case int:  
         fmt.Printf("x is int type")                      
      case float64:
         fmt.Printf("x is float64 type")          
      case func(int) float64:
         fmt.Printf("x is func(int) type")                      
      case bool, string:
         fmt.Printf("x is bool or string type" )      
      default:
         fmt.Printf("Unknown type")    
   }  
}

The execution result of the above code is:

x 的类型 :<nil>

fallthrough

Using fallthrough will forcibly execute the following case statement; fallthrough does not evaluate whether the expression result of the next case is true.

Example

package main

import "fmt"

func main() {

    switch {
    case false:
            fmt.Println("1. The case conditional statement is false")
            fallthrough
    case true:
            fmt.Println("2. The case conditional statement is true")
            fallthrough
    case false:
            fmt.Println(3. The case condition is false)
            fallthrough
    case true:
            fmt.Println(4. The case condition is true)
    case false:
            fmt.Println(5. The case condition is false)
            fallthrough
    default:
            fmt.Println(6. Default case)
    }
}

The execution result of the above code is:

2、case 条件语句为 true
3、case 条件语句为 false
4、case 条件语句为 true

From the output of the above code, it can be seen that switch starts executing from the first case whose evaluation expression is true. If the case has fallthrough, the program will continue to execute the next case, and it will not evaluate whether the expression of the next case is true.

Go language conditional statement

other extensions