Latest web development tutorials

Go language switch statement

Go language conditional statements Go language conditional statements

switch statement is used to perform different actions based on different conditions, each case is unique branch, from up and down individually tested until match. .

Switch statement executes the process from top to bottom, until a match is found, the latter does not need to match plus break

grammar

Syntax Go programming language switch statement is as follows:

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

Var1 variable can be of any type, and val1 and val2 may be any value of the same type. Type is not limited to a constant or an integer, but must be the same type; or the end result is the same type of expression.

You can simultaneously test multiple potentially eligible value, split them with a comma, for example: case val1, val2, val3.

flow chart:

Examples

package main

import "fmt"

func main() {
   /* 定义局部变量 */
   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("优秀!\n" )     
      case grade == "B", grade == "C" :
         fmt.Printf("良好\n" )      
      case grade == "D" :
         fmt.Printf("及格\n" )      
      case grade == "F":
         fmt.Printf("不及格\n" )
      default:
         fmt.Printf("差\n" );
   }
   fmt.Printf("你的等级是 %s\n", grade );      
}

The above code is executed as a result of:

优秀!
你的等级是 A

Type Switch

switch statement can also be used for type-switch variable to determine the type of a variable interface actually stored.

Type Switch syntax is as follows:

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

Examples

package main

import "fmt"

func main() {
   var x interface{}
     
   switch i := x.(type) {
      case nil:	  
         fmt.Printf(" x 的类型 :%T",i)                
      case int:	  
         fmt.Printf("x 是 int 型")                       
      case float64:
         fmt.Printf("x 是 float64 型")           
      case func(int) float64:
         fmt.Printf("x 是 func(int) 型")                      
      case bool, string:
         fmt.Printf("x 是 bool 或 string 型" )       
      default:
         fmt.Printf("未知型")     
   }   
}

The above code is executed as a result of:

x 的类型 :<nil>

Go language conditional statements Go language conditional statements