Golang学习笔记_10——Switch

Golang学习笔记_07------基本类型
Golang学习笔记_08------For循环
Golang学习笔记_09------if条件判断


文章目录

    • Switch语句
      • [1. 基本用法](#1. 基本用法)
      • [2. 多个表达式匹配同一个case](#2. 多个表达式匹配同一个case)
      • [3. 不带表达式的switch(相当于`if-else if-else`)](#3. 不带表达式的switch(相当于if-else if-else))
        • [4. 使用`fallthrough`关键字](#4. 使用fallthrough关键字)
      • [5. Type Switch(类型开关)](#5. Type Switch(类型开关))
      • [6. 注意事项](#6. 注意事项)
    • 源码

Switch语句

1. 基本用法

在Go语言中,switch语句是一种多分支选择结构,用于替代多个if-else语句,使代码更加简洁和易读。switch语句可以基于一个或多个表达式进行匹配,并执行相应的代码块。

go 复制代码
switch expr {
case value1:
    // 当 expr == value1 时执行的代码
case value2:
    // 当 expr == value2 时执行的代码
default:
    // 当 expr 不匹配任何 case 时执行的代码
}
  • expr:要评估的表达式。
  • case valueN:与expr进行比较的值。
  • default:可选的默认分支,当expr不匹配任何case时执行。

举个例子

go 复制代码
func switchDemo(inputNum int) {
	num := inputNum

	switch num {

	case 1:
		fmt.Println("One")
	case 2:
		fmt.Println("Two")
	case 3:
		fmt.Println("Three")
	default:
		fmt.Println("Other")
	}
}

测试方法

GO 复制代码
func Test_switchDemo(t *testing.T) {
	type args struct {
		inputNum int
	}
	tests := []struct {
		name string
		args args
	}{
		{
			name: "1",
			args: args{inputNum: 1},
		},
		{
			name: "other",
			args: args{inputNum: 100},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			switchDemo(tt.args.inputNum)
		})
	}
}

输出结果

复制代码
=== RUN   Test_switchDemo
=== RUN   Test_switchDemo/1
One
=== RUN   Test_switchDemo/other
Other
--- PASS: Test_switchDemo (0.00s)
    --- PASS: Test_switchDemo/1 (0.00s)
    --- PASS: Test_switchDemo/other (0.00s)
PASS

2. 多个表达式匹配同一个case

举个例子

go 复制代码
func mutSwitchDemo(aChar byte) {
	switch aChar {
	case 'a', 'e', 'i', 'o', 'u':
		fmt.Println("Vowel")
	default:
		fmt.Println("Consonant")
	}
}

测试方法

go 复制代码
func Test_mutSwitchDemo(t *testing.T) {
	type args struct {
		aChar byte
	}
	tests := []struct {
		name string
		args args
	}{
		{
			name: "a",
			args: args{aChar: 'a'},
		},
		{
			name: "z",
			args: args{aChar: 'z'},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			mutSwitchDemo(tt.args.aChar)
		})
	}
}

输出结果

复制代码
=== RUN   Test_mutSwitchDemo
=== RUN   Test_mutSwitchDemo/a
Vowel
=== RUN   Test_mutSwitchDemo/z
Consonant
--- PASS: Test_mutSwitchDemo (0.00s)
    --- PASS: Test_mutSwitchDemo/a (0.00s)
    --- PASS: Test_mutSwitchDemo/z (0.00s)
PASS

3. 不带表达式的switch(相当于if-else if-else

举个例子

go 复制代码
func noSwitchDemo(inputNum int) {
	num := inputNum
	switch {
	case num < 0:
		fmt.Println("Negative")
	case num == 0:
		fmt.Println("Zero")
	case num > 0:
		fmt.Println("Positive")
	}
}

测试方法

go 复制代码
func Test_noSwitchDemo(t *testing.T) {
	type args struct {
		inputNum int
	}
	tests := []struct {
		name string
		args args
	}{
		{
			name: "Negative",
			args: args{inputNum: -100},
		},
		{
			name: "zero",
			args: args{inputNum: 0},
		},
		{
			name: "Positive",
			args: args{inputNum: 100},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			noSwitchDemo(tt.args.inputNum)
		})
	}
}

输出结果

复制代码
=== RUN   Test_noSwitchDemo
=== RUN   Test_noSwitchDemo/Negative
Negative
=== RUN   Test_noSwitchDemo/zero
Zero
=== RUN   Test_noSwitchDemo/Positive
Positive
--- PASS: Test_noSwitchDemo (0.00s)
    --- PASS: Test_noSwitchDemo/Negative (0.00s)
    --- PASS: Test_noSwitchDemo/zero (0.00s)
    --- PASS: Test_noSwitchDemo/Positive (0.00s)
PASS
4. 使用fallthrough关键字

fallthrough关键字会使程序继续执行下一个case语句,即使当前case已经匹配成功。

go 复制代码
func fullThroughDemo(inputNum int) {
	num := inputNum
	switch num {
	case 1:
		fmt.Println("One")
		fallthrough
	case 2:
		fmt.Println("Two (fallthrough)")
	case 3:
		fmt.Println("Three")
	default:
		fmt.Println("Other")
	}
}

测试方法

go 复制代码
func Test_fullThroughDemo(t *testing.T) {
	type args struct {
		inputNum int
	}
	tests := []struct {
		name string
		args args
	}{
		{
			name: "1",
			args: args{inputNum: 1},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			fullThroughDemo(tt.args.inputNum)
		})
	}
}

输出结果

复制代码
=== RUN   Test_fullThroughDemo
=== RUN   Test_fullThroughDemo/1
One
Two (fallthrough)
--- PASS: Test_fullThroughDemo (0.00s)
    --- PASS: Test_fullThroughDemo/1 (0.00s)
PASS

5. Type Switch(类型开关)

举个例子

go 复制代码
func typeSwitchDemo(i interface{}) {

	switch v := i.(type) {
	case int:
		fmt.Printf("Type is int: %d\n", v)
	case string:
		fmt.Printf("Type is string: %s\n", v)
	case bool:
		fmt.Printf("Type is bool: %t\n", v)
	default:
		fmt.Println("Unknown type")
	}
}

测试方法

go 复制代码
func Test_typeSwitchDemo(t *testing.T) {
	type args struct {
		i interface{}
	}
	tests := []struct {
		name string
		args args
	}{
		{
			name: "bool",
			args: args{i: true},
		},
		{
			name: "int",
			args: args{i: 1},
		},
		{
			name: "string",
			args: args{i: "hello"},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			typeSwitchDemo(tt.args.i)
		})
	}
}

输出结果

复制代码
=== RUN   Test_typeSwitchDemo
=== RUN   Test_typeSwitchDemo/bool
Type is bool: true
=== RUN   Test_typeSwitchDemo/int
Type is int: 1
=== RUN   Test_typeSwitchDemo/string
Type is string: hello
--- PASS: Test_typeSwitchDemo (0.00s)
    --- PASS: Test_typeSwitchDemo/bool (0.00s)
    --- PASS: Test_typeSwitchDemo/int (0.00s)
    --- PASS: Test_typeSwitchDemo/string (0.00s)
PASS

6. 注意事项

  1. switchcase 语句从上到下顺次执行,直到匹配成功时停止。
  2. 每个case块以break隐式结束 :在Go语言中,每个case块在执行完毕后会自动跳出switch语句,因此不需要显式地使用break
  3. fallthrough的使用fallthrough关键字是可选的,并且通常不常用,因为它会使代码的逻辑变得复杂。
  4. 类型开关:类型开关是Go语言特有的功能,非常适用于处理接口类型的变量。

源码

go 复制代码
// switch_demo.go 文件
package switch_demo

import "fmt"

func switchDemo(inputNum int) {
	num := inputNum

	switch num {

	case 1:
		fmt.Println("One")
	case 2:
		fmt.Println("Two")
	case 3:
		fmt.Println("Three")
	default:
		fmt.Println("Other")
	}
}

func mutSwitchDemo(aChar byte) {
	switch aChar {
	case 'a', 'e', 'i', 'o', 'u':
		fmt.Println("Vowel")
	default:
		fmt.Println("Consonant")
	}
}

func noSwitchDemo(inputNum int) {
	num := inputNum
	switch {
	case num < 0:
		fmt.Println("Negative")
	case num == 0:
		fmt.Println("Zero")
	case num > 0:
		fmt.Println("Positive")
	}
}

func fullThroughDemo(inputNum int) {
	num := inputNum
	switch num {
	case 1:
		fmt.Println("One")
		fallthrough
	case 2:
		fmt.Println("Two (fallthrough)")
	case 3:
		fmt.Println("Three")
	default:
		fmt.Println("Other")
	}
}

func typeSwitchDemo(i interface{}) {

	switch v := i.(type) {
	case int:
		fmt.Printf("Type is int: %d\n", v)
	case string:
		fmt.Printf("Type is string: %s\n", v)
	case bool:
		fmt.Printf("Type is bool: %t\n", v)
	default:
		fmt.Println("Unknown type")
	}
}
go 复制代码
// switch_demo_test.go
package switch_demo

import (
	"testing"
)

func Test_switchDemo(t *testing.T) {
	type args struct {
		inputNum int
	}
	tests := []struct {
		name string
		args args
	}{
		{
			name: "1",
			args: args{inputNum: 1},
		},
		{
			name: "other",
			args: args{inputNum: 100},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			switchDemo(tt.args.inputNum)
		})
	}
}

func Test_mutSwitchDemo(t *testing.T) {
	type args struct {
		aChar byte
	}
	tests := []struct {
		name string
		args args
	}{
		{
			name: "a",
			args: args{aChar: 'a'},
		},
		{
			name: "z",
			args: args{aChar: 'z'},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			mutSwitchDemo(tt.args.aChar)
		})
	}
}

func Test_noSwitchDemo(t *testing.T) {
	type args struct {
		inputNum int
	}
	tests := []struct {
		name string
		args args
	}{
		{
			name: "Negative",
			args: args{inputNum: -100},
		},
		{
			name: "zero",
			args: args{inputNum: 0},
		},
		{
			name: "Positive",
			args: args{inputNum: 100},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			noSwitchDemo(tt.args.inputNum)
		})
	}
}

func Test_fullThroughDemo(t *testing.T) {
	type args struct {
		inputNum int
	}
	tests := []struct {
		name string
		args args
	}{
		{
			name: "1",
			args: args{inputNum: 1},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			fullThroughDemo(tt.args.inputNum)
		})
	}
}

func Test_typeSwitchDemo(t *testing.T) {
	type args struct {
		i interface{}
	}
	tests := []struct {
		name string
		args args
	}{
		{
			name: "bool",
			args: args{i: true},
		},
		{
			name: "int",
			args: args{i: 1},
		},
		{
			name: "string",
			args: args{i: "hello"},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			typeSwitchDemo(tt.args.i)
		})
	}
}
相关推荐
weixin_4316004442 分钟前
Agent Workflow 学习向:Code 节点,比模板更强的变量加工
后端·python·学习·ai·
Xuanzang Road2 小时前
第 40 届学习强企玄奘路戈壁挑战赛:在绝境中重塑自我
学习
tju新生代魔迷3 小时前
Python学习日记3
学习
hsjiasb4 小时前
FreeRTOS学习(三十九)——最终总结
学习·学习笔记·freertos
m4Rk_5 小时前
【论文阅读】Agent 记忆机制(47):Nemori——用“预测误差”判断什么经验值得被记住
论文阅读·人工智能·学习·开源·github
互联网中的一颗神经元5 小时前
06. Small 对象分配:mcache 无锁路径
开发语言·golang
约克35 小时前
2024年空调除甲醛技术参数与性能评测解析
学习
kkkkkkkkkk_Z5 小时前
学嵌入式和C语言编程数据结构|学习日记Day21:内核链表与队列学习
c语言·数据结构·学习
GGMM7896 小时前
VX4B600100 控制板全解析:施耐德 ATV630 变频器核心控制单元详解
笔记·变频器·变频器维修
kdxiaojie7 小时前
Linux USB驱动阅读笔记(1)
linux·笔记·学习·usb