条件语句需要开发者通过指定一个或多个条件,并通过测试条件是否为 true 来决定是否执行指定语句,并在条件为 false 的情况在执行另外的语句
下图展示了程序语言中条件语句的结构:
Go 语言提供的几种条件判断语句
| 语句 | 描述 |
|---|---|
| if 语句 | if 语句 由一个布尔表达式后紧跟一个或多个语句组成。 |
| if…else 语句 | if 语句 后可以使用可选的 else 语句, else 语句中的表达式在布尔表达式为 false 时执行。 |
| if 嵌套语句 | 你可以在 if 或 else if 语句中嵌入一个或多个 if 或 else if 语句。 |
| switch 语句 | switch 语句用于基于不同条件执行不同动作。 |
| select 语句 | select 语句类似于 switch 语句,但是select会随机执行一个可运行的case。如果没有case可运行,它将阻塞,直到有case可运行。 |
⚠️ 注意: Go 没有三目运算符,所以不支持 condition ? expr1 : expr2 形式的条件判断
if 语句
if 语句由布尔表达式后紧跟一个或多个语句组成
语法
Go 编程语言中 if 语句的语法如下:
if 布尔表达式 {/* 在布尔表达式为 true 时执行 */}
If 在布尔表达式为 true 时,其后紧跟的语句块执行,如果为 false 则不执行。流程图如下:
使用 if 判断一个数变量的大小
package mainimport "fmt"func main() {/* 定义局部变量 */var a int = 10/* 使用 if 语句判断布尔表达式 */if a < 20 {/* 如果条件为 true 则执行以下语句 */fmt.Printf("a 小于 20\n" )}fmt.Printf("a 的值为 : %d\n", a)}/*a 小于 20a 的值为 : 10*/
if…else 语句
if 语句 后可以使用可选的 else 语句, else 语句中的表达式在布尔表达式为 false 时执行
语法
Go 编程语言中 if…else 语句的语法如下:
if 布尔表达式 {/* 在布尔表达式为 true 时执行 */} else {/* 在布尔表达式为 false 时执行 */}
If 在布尔表达式为 true 时,其后紧跟的语句块执行,如果为 false 则执行 else 语句块。流程图如下:
使用 if else 判断一个数的大小
package mainimport "fmt"func main() {/* 局部变量定义 */var a int = 100;/* 判断布尔表达式 */if a < 20 {/* 如果条件为 true 则执行以下语句 */fmt.Printf("a 小于 20\n" );} else {/* 如果条件为 false 则执行以下语句 */fmt.Printf("a 不小于 20\n" );}fmt.Printf("a 的值为 : %d\n", a);}/*a 不小于 20a 的值为 : 100*/
寻找到 100 以内的所有的素数
package mainimport "fmt"func main(){// var count,c int //定义变量不使用也会报错var count int =1var flag bool//while(count<100) { //go没有whilefor count < 100 {count++flag = true;//注意tmp变量 :=for tmp:=2;tmp<count;tmp++ {if count%tmp==0{flag = false}}// 每一个 if else 都需要加入括号 同时 else 位置不能在新一行if flag == true {fmt.Println(count,"素数")}else{continue}}}
if … else if … else…
语法
if 布尔表达式 {/* 在布尔表达式为 true 时执行 */} else if 布尔表达式 {/* 在布尔表达式为 false 时执行 */}else {/* 在布尔表达式为 false 时执行 */}
示例
package mainimport "fmt"func main() {var age int = 23if age == 25 {fmt.Println("true")} else if age < 25 {fmt.Println("too small")} else {fmt.Println("too big")}}/*too small*/
if 语句嵌套
你可以在 if 或 else if 语句中嵌入一个或多个 if 或 else if 语句
语法
Go 编程语言中 if…else 语句的语法如下:
if 布尔表达式 1 {/* 在布尔表达式 1 为 true 时执行 */if 布尔表达式 2 {/* 在布尔表达式 2 为 true 时执行 */}}
你可以以同样的方式在 if 语句中嵌套 else if…else 语句
package mainimport "fmt"func main() {/* 定义局部变量 */var a int = 100var b int = 200/* 判断条件 */if a == 100 {/* if 条件语句为 true 执行 */if b == 200 {/* if 条件语句为 true 执行 */fmt.Printf("a 的值为 100 , b 的值为 200\n" );}}fmt.Printf("a 值为 : %d\n", a );fmt.Printf("b 值为 : %d\n", b );}/*a 的值为 100 , b 的值为 200a 值为 : 100b 值为 : 200*/
switch 语句
switch 语句用于基于不同条件执行不同动作,每一个 case 分支都是唯一的,从上至下逐一测试,直到匹配为止 switch 语句执行的过程从上至下,直到找到匹配项,匹配项后面也不需要再加 break。 switch 默认情况下 case 最后自带 break 语句,默认只会执行匹配到的那个 case,匹配成功后就不会执行其他 case,如果我们需要执行后面的 case,可以使用 fallthrough
语法
Go 编程语言中 switch 语句的语法如下:
switch val1 {case val1:...case val2:...default:...}
变量 val1 可以是任何类型,而 val1 和 val2 则可以是同类型的任意值。类型不被局限于常量或整数,但必须是相同的类型;或者最终结果为相同类型的表达式。
您可以同时测试多个可能符合条件的值,使用逗号分割它们,支持多条件匹配。例如:case val1, val2, val3
switch{case 1,2,3,4:...default:...}
/
package mainimport "fmt"func main() {/* 定义局部变量 */var grade string = "B"var marks int = 90switch marks {case 90: grade = "A"case 80: grade = "B"case 50,60,70 : grade = "C"default: grade = "D"}switch {case grade == "A" :fmt.Printf("优秀!\n" )case grade == "B", grade == "C" :fmt.Printf("良好\n" )case grade == "D" :fmt.Printf("及格\n" )case grade == "F":fmt.Printf("不及格\n" )default:fmt.Printf("差\n" );}fmt.Printf("你的等级是 %s\n", grade );}/*优秀!你的等级是 A*/
Type Switch
switch 语句还可以被用于 type-switch 来判断某个 interface 变量中实际存储的变量类型。Type Switch 语法格式如下:
switch x.(type){case type:statement(s);case type:statement(s);/* 你可以定义任意个数的case */default: /* 可选 */statement(s);}
package mainimport "fmt"func main() {var x interface{}switch i := x.(type) {case nil:fmt.Printf(" x 的类型 :%T",i)case int:fmt.Printf("x 是 int 型")case float64:fmt.Printf("x 是 float64 型")case func(int) float64:fmt.Printf("x 是 func(int) 型")case bool, string:fmt.Printf("x 是 bool 或 string 型" )default:fmt.Printf("未知型")}}/*x 的类型 :<nil>*/
fallthrough
使用 fallthrough 会强制执行后面的 case 语句,fallthrough 不会判断下一条 case 的表达式结果是否为 true
package mainimport "fmt"func main() {switch {case false:fmt.Println("1、case 条件语句为 false")fallthroughcase true:fmt.Println("2、case 条件语句为 true")fallthroughcase false:fmt.Println("3、case 条件语句为 false")fallthroughcase true:fmt.Println("4、case 条件语句为 true")case false:fmt.Println("5、case 条件语句为 false")fallthroughdefault:fmt.Println("6、默认 case")}}/*2、case 条件语句为 true3、case 条件语句为 false4、case 条件语句为 true*/
break
如果想要执行多个 case,需要使用 fallthrough 关键字,也可用 break 终止
switch{case 1:...if(...){break}fallthrough // 此时switch(1)会执行case1和case2,但是如果满足if条件,则只执行case1case 2:...case 3:...default:...}
经典案例
package mainimport ("fmt")func main() {a := 1switch a {case 0:fmt.Println("a = 0 ")case 1:fmt.Println("a = 1")default:fmt.Println("Unknown")}}/*运行结果a = 1*/
switch后带初始化表达式
支持一个初始化表达式(可以是并行方式),右侧需跟分号
package mainimport ("fmt""strconv")func main() {var a string ="100"switch ascapegoat, _ := strconv.ParseInt(a, 10, 64);{case ascapegoat>90:fmt.Println("优秀")case ascapegoat>80:fmt.Println("良好")case ascapegoat>70:fmt.Println("中上")case ascapegoat>=60:fmt.Println("及格")case ascapegoat<60:fmt.Println("丢人")default:fmt.Println("系统出错")}}/*string到intint,err:=strconv.Atoi(string)string到int64int64, err := strconv.ParseInt(string, 10, 64)int到stringstring:=strconv.Itoa(int)int64到stringstring:=strconv.FormatInt(int64,10)*//*优秀*/
switch后不带任何条件与表达式
可以使用任何类型或表达式作为条件语句;
不需要写break,一旦条件符合自动终止;
若希望继续执行下一个case,需使用fallthrough语句
package mainimport ("fmt")func main() {var a = 8switch {case a >= 0:fmt.Println("a >= 0 ")fallthroughcase a >= 5:fmt.Println("a >= 5")fallthroughdefault:fmt.Println("Unknown")}}/*a >= 0a >= 5Unknown*/
select 语句
select 是 Go 中的一个控制结构,类似于用于通信的 switch 语句。每个 case 必须是一个通信操作,要么是发送要么是接收 select 随机执行一个可运行的 case。如果没有 case 可运行,它将阻塞,直到有 case 可运行。一个默认的子句应该总是可运行的
语法
Go 编程语言中 select 语句的语法如下:
select {case communication clause :statement(s);case communication clause :statement(s);/* 你可以定义任意数量的 case */default : /* 可选 */statement(s);}
以下描述了 select 语句的语法:
- 每个 case 都必须是一个通信
- 所有 channel 表达式都会被求值
- 所有被发送的表达式都会被求值
- 如果任意某个通信可以进行,它就执行,其他被忽略。
- 如果有多个 case 都可以运行,Select 会随机公平地选出一个执行。其他不会执行。否则:
- 如果有 default 子句,则执行该语句
- 如果没有 default 子句,select 将阻塞,直到某个通信可以运行;Go 不会重新对 channel 或值进行求值 ```go package main import “fmt”
func main() { var c1, c2, c3 chan int var i1, i2 int
select {
case i1 = <-c1:
fmt.Printf(“received “, i1, “ from c1\n”)
case c2 <- i2:
fmt.Printf(“sent “, i2, “ to c2\n”)
case i3, ok := (<-c3): // same as: i3, ok := <-c3
if ok {
fmt.Printf(“received “, i3, “ from c3\n”)
} else {
fmt.Printf(“c3 is closed\n”)
}
default:
fmt.Printf(“no communication\n”)
}
}
/ no communication /
select 会循环检测条件,如果有满足则执行并退出,否则一直循环检测```gopackage mainimport ("fmt""time")func Chann(ch chan int, stopCh chan bool) {// var i int = 10for j := 0; j < 10; j++ {ch <- jtime.Sleep(time.Second)}stopCh <- true}func main() {ch := make(chan int)c := 0stopCh := make(chan bool)go Chann(ch, stopCh)for {select {case c = <-ch:fmt.Printf("C = <-ch Recvice %d\n", c)fmt.Println("channel")case s := <-ch:fmt.Printf("S := <-ch Receive %d\n", s)case _ = <-stopCh:goto end}}end:fmt.Println("程序运行结束")}/*S := <-ch Receive 0C = <-ch Recvice 1channelS := <-ch Receive 2C = <-ch Recvice 3channelC = <-ch Recvice 4channelS := <-ch Receive 5C = <-ch Recvice 6channelS := <-ch Receive 7C = <-ch Recvice 8channelS := <-ch Receive 9程序运行结束*/
