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

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

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/go/go-switch-statement.html

来源:LearnFk无涯教程网

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

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

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/go/go-switch-statement.html

来源:LearnFk无涯教程网

type of x :<nil>

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

技术教程推荐

Python核心技术与实战 -〔景霄〕

DDD实战课 -〔欧创新〕

Service Mesh实战 -〔马若飞〕

爆款文案修炼手册 -〔乐剑峰〕

李智慧 · 高并发架构实战课 -〔李智慧〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

结构会议力 -〔李忠秋〕

程序员职业规划手册 -〔雪梅〕

云原生基础架构实战课 -〔潘野〕

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