Loading

Go语言之循环与条件判断

一、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 == 11, num == 12:
   fmt.Println(11, 12)
   fallthrough
case num == 40, num == 44:
   fmt.Println(40, 44)
   fallthrough
default:
   fmt.Println("无匹配")
}

// 输出
11 12
40 44
无匹配
posted @ 2021-10-07 13:16  Mr-Yang`  阅读(257)  评论(0编辑  收藏  举报