Go语言之循环与条件判断
2021-10-07 13:16
826 查看
一、for循环
Go 语言中没有 while 循环,只有一个 for 循环
for 变量初始化;条件;变量自增/自减 { 循环体内容 }
1、基本使用
for i := 0; i < 10; i++ { fmt.Println(i) }
2、省略第一部分
i := 0 for ; i < 10; i++ { fmt.Println(i) }
3、省略第一和三部分(这是一个 while 循环) for 条件 { 循环体内容 }
i := 0 for i < 10 { fmt.Println(i) i++ }
4、死循环
for { fmt.Println("死循环") }
5、开多协程演示
for i := 0; i < 2000; i++ { go test() } func test() { for { fmt.Println("死循环") } }
6、break:结束本次 for 循环,continue 结束本次循环,继续下一次循环
二、Switch语句
Switch 是一个条件语句,用于将表达式的值与可能匹配的选项列表进行比较,并根据匹配情况执行相应的代码块,它可以被认为是替代多个 if else 语句的常用方式
1、基本使用
num := 4 switch num { case 1: fmt.Println("1") case 2: fmt.Println("2") case 3: fmt.Println("3") case 4: fmt.Println("4") } // 输出 4
2、默认情况(都没有匹配上)
num := 5 switch num { case 1: fmt.Println("1") case 2: fmt.Println("2") case 3: fmt.Println("3") case 4: fmt.Println("4") default: fmt.Println("都没有匹配上") } // 输出 都没有匹配上
3、多表达式判断
num := 44 switch num { case 11, 12, 13, 14: fmt.Println("1") case 21, 22: fmt.Println("2") case 31, 33: fmt.Println("3") case 40, 43, 44: fmt.Println("4") default: fmt.Println("都没有匹配上") } // 输出 4
4、无表达式的 Switch
num := 44 switch { case num == 11, num == 12: fmt.Println(11, 12) case num == 40, num == 44: fmt.Println(40, 44) } // 输出 40 44
5、Fallthrough(穿透,只要看到 fallthrough,无条件执行下一个 case 或者 default )
num := 12 switch { case num == 1 56c 1, num == 12: fmt.Println(11, 12) fallthrough case num == 40, num == 44: fmt.Println(40, 44) fallthrough default: fmt.Println("无匹配") } // 输出 11 12 40 44 无匹配
相关文章推荐
- GO语言学习笔记1(基本概念,条件循环语句)
- go语言渐入佳境[7]-if判断条件
- D2:编码、格式化语言、列表、条件判断、循环、访问元素(dictionary)
- 5.go语言条件语句和循环语句
- Python 语言基础四_条件判断与循环
- Go 语言条件语句和循环语句
- Go语言基础篇(4) —— Go语言循环&判断&选择语句
- Go语言学习笔记 --- 控制语句之if判断,循环语句for, switch语句和跳转语句
- Go语言循环判断的使用~
- Go语言学习三 :循环语句
- 无符号数(unsigned) 和带符号数(int)的循环变量 在for循环条件判断使用中的区别1例
- 【Python⑥】python的缩进,条件判断和循环
- 20180403-Python if条件判断及while循环
- Python条件循环判断
- python基础之python条件判断和循环
- if-elif条件判断,while循环和for…in循环
- Go 语言中数据类型的判断
- MySql存储过程—逻辑判断,条件控制,循环控制
- 【剑指offer】实现 1+2+3+...+n,要求不能使用乘除法,循环,条件判断,选择相关的关键字
- MySQL条件判断和循环语句