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)
		})
	}
}
相关推荐
一只路人甲11 小时前
使用AI快速学习
学习
传奇开心果编程12 小时前
【Rust入门练中学】第2课:变量、可变性与常量
开发语言·学习·rust
边境悍匪14 小时前
蜗牛学苑 Java 智能体学习 Day42|项目周开发技术汇总 1 思维导图复盘
java·开发语言·spring boot·学习·spring
Gyr015 小时前
浅刷了一遍51CTO软考题库客观题及其解析(4)
学习·软考·知识点·信息安全工程师
是隼人15 小时前
buuctf-pwn [NewStarCTF 2023 公开赛道]stack migration(64位栈迁移)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
ι:16 小时前
单相桥式全控整流仿真从零复现教学
windows·学习·matlab·simulink
CAYA-16 小时前
模电笔记1.1 半导体基础与 PN 结
经验分享·笔记·学习方法
传奇开心果编程16 小时前
【Rust入门练中学】 第3课:数据类型
开发语言·学习·rust
humors22116 小时前
今年我正在看、看完和还没看的书单(不定期更新)
学习·阅读·读书·书单·书籍
泡泡鱼(敲代码中)17 小时前
MySQL 学习笔记:DCL、函数与约束 —— 安全、效率、完整性的三板斧
开发语言·笔记·sql·学习·mysql·gitee