GO语言语法---switch语句

文章目录

  • 基本语法
  • [1. 特点](#1. 特点)
    • [1.1 不需要break](#1.1 不需要break)
    • [1.2 表达式可以是任何类型](#1.2 表达式可以是任何类型)
    • [1.3 省略比较表达式](#1.3 省略比较表达式)
    • [1.4 多值匹配](#1.4 多值匹配)
    • [1.5 类型switch](#1.5 类型switch)
    • [1.6 case穿透](#1.6 case穿透)
    • [1.7 switch后直接声明变量](#1.7 switch后直接声明变量)
      • [1.7.1 基本语法](#1.7.1 基本语法)
      • [1.7.2 带比较表达式](#1.7.2 带比较表达式)
      • [1.7.3 不带比较表达式](#1.7.3 不带比较表达式)
      • [1.7.4 结合类型判断](#1.7.4 结合类型判断)
    • [1.8 switch后的表达式必须与case语句中的表达式类型一致](#1.8 switch后的表达式必须与case语句中的表达式类型一致)

Go语言的switch语句是一种多分支选择结构,比传统的if-else链更清晰。Go中的switch有一些独特的特性。

基本语法

go 复制代码
switch expression {
case value1:
    // 代码块
case value2:
    // 代码块
default:
    // 默认代码块
}

1. 特点

1.1 不需要break

Go的switch case默认不会"贯穿"(fallthrough),执行完一个case后会自动退出switch。因此不需要和C语言一样在每个case语句之后写break。

1.2 表达式可以是任何类型

表达式可以是任何类型,不限于整数或常量。表达式可以是函数,也可以是逻辑判断,设置可以是字符串和浮点数。

代码如下:

go 复制代码
	// 表达式为字符串
	var str = "nihao"
	switch str {
		case "hl":
    		fmt.Printf("hl\n")
		case "nihao":
    		fmt.Printf("nihao\n")
		default:
    		fmt.Printf("err\n")
	}
	
	// 表达式为浮点数
	var my_float = 20.3
	switch my_float {
		case 20.1:
    		fmt.Printf("20.1\n")
		case 20.3:
    		fmt.Printf("20.3\n")
		default:
    		fmt.Printf("err\n")
	}
	
	// 表达式为逻辑判断
	switch 1 < 2 {
		case true:
    		fmt.Printf("true\n")
		case false:
    		fmt.Printf("false\n")
		default:
    		fmt.Printf("err\n")
	}
	
	// 表达式为函数
	switch my_func() {
		case 1:
    		fmt.Printf("1\n")
		case 2:
    		fmt.Printf("2\n")
		default:
    		fmt.Printf("err\n")
	}
	
	func my_func() uint8{
		return 2;
	}

运行结果:

go 复制代码
nihao
20.3
true
2

1.3 省略比较表达式

代码如下:

go 复制代码
/* 省略表达式的形式 可代替if-else结构 */
	var score = 80

	switch {
		case score >= 90:
    		fmt.Println("优秀")
		case score >= 80:
    		fmt.Println("良好")
		default:
    		fmt.Println("一般")
	}

运行结果:

go 复制代码
良好

1.4 多值匹配

代码如下:

go 复制代码
	/* 多值匹配 */
	var day = 7

	switch day {
		case 6, 7:
    		fmt.Println("周末")
		case 2, 3, 4, 5, 1:
    		fmt.Println("工作日")
	}

运行结果:

bash 复制代码
周末

C语言实现多值匹配:

c 复制代码
switch (day) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        printf("工作日\n");
        break;
   case 6:
   case 7:
    printf("周末\n");
    break;
}

1.5 类型switch

代码如下:

go 复制代码
	/* 类型switch */
	var x interface{} = "hello"
	var y interface{} = 5

	switch x.(type) {
		case int:
    		fmt.Println("整数")
		case string:
    		fmt.Println("字符串")
		default:
    		fmt.Println("未知类型")
	}

	switch y.(type) {
		case int:
    		fmt.Println("整数")
		case string:
    		fmt.Println("字符串")
		default:
    		fmt.Println("未知类型")
	}

运行结果:

bash 复制代码
字符串
整数

1.6 case穿透

go语言没有break,执行完case语句默认跳出switch语句。但是如果使用fallthrough,可穿透case,即执行完当前case语句不直接跳出switch语句,将不进行判断直接进入下一个case语句执行。

代码如下:

go 复制代码
	var n = 1
	switch n {
		case 1:
    		fmt.Println("n = 1")
    		fallthrough
		case 2:
    		fmt.Println("n <= 2")
		case 3:
    		fmt.Println("n = 3")
	}

运行结果:

bash 复制代码
字符串
n = 1
n <= 2

1.7 switch后直接声明变量

1.7.1 基本语法

c 复制代码
switch variable := expression; variable {
case value1:
    // 使用variable
case value2:
    // 使用variable
default:
    // 使用variable
}

1.7.2 带比较表达式

go 复制代码
	/* switch后直接声明变量,带比较表达式 */
	switch num := 5; num {
		case 1:
    		fmt.Println("One")
		case 2:
    		fmt.Println("Two")
		default:
    		fmt.Println("Unknown number:", num)
		}

运行结果:

bash 复制代码
Unknown number: 5

1.7.3 不带比较表达式

go 复制代码
	/* switch后直接声明变量,不带比较表达式 */
	switch age := 18; {
		case age < 18: 
    		fmt.Println("未成年")
		case age >= 18 && age < 60:
    		fmt.Println("成年人")
		default:
    		fmt.Println("老年人")
		}

运行结果:

bash 复制代码
成年人

1.7.4 结合类型判断

go 复制代码
	/* switch后直接声明变量,不带比较表达式,结合类型判断 */
	var x interface{} = "hello"
	switch v := x.(type) {
		case int:
    		fmt.Printf("整型: %d\n", v)
		case string:
    		fmt.Printf("字符串: %s\n", v)
		default:
    		fmt.Printf("未知类型: %v\n", v)
}

运行结果:

bash 复制代码
字符串: hello

1.8 switch后的表达式必须与case语句中的表达式类型一致

switch后的表达式和case语句中的表达式是要做比较动作的,因此类型需要报错一致,在
Go语言运算符详解

中的注意事项中提到,不同类型的值不能直接运算,必须显式转换。

如下图代码所示:str是string类型,20.1和20.3是浮点型,因此报错。

相关推荐
平头哥AI16 小时前
Day 01 | go run 跑通第一个 Go 程序,go build 留下一个能拷走的 exe
开发语言·后端·golang
2601_9622965117 小时前
如何使用Golang包路径_管理本地和远程模块引用
golang·数据转换·变量定义·常用库·编程语言区别
FfHUCisI1 天前
GMP 调度器:Go 并发的心脏是如何跳动的
开发语言·golang·php
我不会起名字3221 天前
一天一道算法题(26):栈的简单应用
java·数据结构·python·算法·leetcode·golang·
gsls2008081 天前
告别 Vault 的复杂度:用 Go 标准库给 Windows 凭据管理器装上 MCP
windows·golang·mcp
名字还没想好☜1 天前
Go 时间格式化为什么用 2006-01-02:time.Format/Parse 的参考时间、时区与解析踩坑
开发语言·后端·golang·go
FfHUCisI2 天前
Golang Map 哈希表实现
golang·哈希算法·散列表
源代码•宸2 天前
前置准备:定时微服务背景和现状
开发语言·经验分享·后端·微服务·云原生·架构·golang
李燚2 天前
把规则搬回家:三个 BC 的贫血→充血重构实录(第103篇)
golang·agent·ddd·领域驱动设计·eino·deepflux·eino adk
astronautyi2 天前
Go 运行时内存分配与 GC 位图深度剖析
开发语言·后端·golang