Go 中的 switch 语句函数

首页 / Golang入门教程 / Go 中的 switch 语句函数

switch 语句允许针对值列表对变量进行相等性测试。

switch - 语法

Go编程语言中 expression switch 语句的语法如下-

switch(boolean-expression or integral type){
   case boolean-expression or integral type :
      statement(s);      
   case boolean-expression or integral type :
      statement(s); 
   
   /* 你可以有任意数量的case语句 */
   default : /* 可选 */
      statement(s);
}

switch - 流程图

switch statement in Go

switch - 示例

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("Excellent!\n" )     
      case grade == "B", grade == "C" :
         fmt.Printf("Well done\n" )      
      case grade == "D" :
         fmt.Printf("You passed\n" )      
      case grade == "F":
         fmt.Printf("Better try again\n" )
      default:
         fmt.Printf("Invalid grade\n" );
   }
   fmt.Printf("Your grade is  %s\n", grade );      
}

编译并执行上述代码后,将产生以下输出-

Excellent!
Your grade is  A

Type Switch - 语法

Go编程中 type switch 语句的语法如下-

switch x.(type){
   case type:
      statement(s);      
   case type:
      statement(s); 
   /* 可多个case选项 */
   default: /* 可选 */
      statement(s);
}

Type Switch - 示例

package main

import "fmt"

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

编译并执行上述代码后,将产生以下输出-

type of x :<nil>

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

持续交付36讲 -〔王潇俊〕

大规模数据处理实战 -〔蔡元楠〕

技术管理案例课 -〔许健〕

Django快速开发实战 -〔吕召刚〕

如何落地业务建模 -〔徐昊〕

说透元宇宙 -〔方军〕

高并发系统实战课 -〔徐长龙〕

手把手教你落地DDD -〔钟敬〕

结构执行力 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)