条件判断
# 条件判断
条件语句一般指定一个或多个条件,并通过测试条件是否为 true 来决定是否执行指定语句,并在条件为 false 的情况在执行另外的语句。
# 01 条件判断 if
Golang 中 if 条件语句通过 if
关键字声明,声明条件可以省略条件表达式的括号,但是条件语句的代码块左大括号 {
必须在条件表达式的末尾,否则会触发编译错误。
// 声明语法
if 条件表达式 {
/* 在条件表达式为 true 时执行 */
}
// example:
func IfExp() {
var x int = 10
// if x > 10 // 编译出错
// {
// fmt.Println("con't print here")
// }
if x >= 10 {
fmt.Println("x 大于等于 10")
}
}
else
关键字和 if
对应在条件表达式为 false
时执行其代码块; else if
是 if
的延伸,与多个 if
判断不同的是 else if
与其关联的 if
互斥执行,而前者是相互独立执行的。
func IfExp() {
var x int = 10
if x != 10 {
fmt.Println("x 不等于 10")
} else {
fmt.Println("x 等于 10")
}
y := 20
if x == 10 {
fmt.Println("x 等于 10")
} else if y == 20 {
fmt.Println("y 等于 20")
} else {
fmt.Println("x 不等于 10")
}
if x == 10 {
fmt.Println("x 等于 10")
}
if y == 20 {
fmt.Println("y 等于 20")
}
}
Golang 中可以在 if 条件表达式之前添加执行语句,再根据执行语句的变量值进行判断。这种特殊写法引出了变量作用域的问题,上述执行语句中的变量仅在 if 局部代码块内生效,不影响外部的变量。
在编程中,变量在其实现了变量的功能后,作用范围越小,所造成的问题可能性越小,每一个变量代表一个状态,有状态的地方,状态就会被修改,函数的局部变量只会影响一个函数的执行,但全局变量可能会影响所有代码的执行状态,因此限制变量的作用范围对代码的稳定性有很大的帮助。
func IfExp() {
var x int = 10
if x := subFunc(); x == 1 {
fmt.Println("x 等于 1")
x -= 1
fmt.Println("inner x:", x)
} else {
fmt.Println("x 等于 10")
}
fmt.Println("global x:", x)
}
func subFunc() int {
return 1
}
/* output:
x 等于 1
inner x: 0
global x: 10
*/
# 02 分支选择 switch
switch
分支选择可以理解为一种批量的 if
语句,根据不同的条件执行不同的代码块,使用switch语句可方便地对大量的值进行判断。
区别于 C/C++ 中 switch 语句只能进行常量判断,Golang 中 switch 的分支表达式可以是任意类型,且在每个唯一的 case 分支代码块相互独立,可以省略 break 跳出操作,默认自动终止。
func SwitchExp() {
var num int = 1
switch num {
case 0:
fmt.Println("case 0")
case 1:
fmt.Println("case 1")
case 2:
fmt.Println("case 2")
}
}
同分支合并:如果多个不同 case 的代码执行任务一致,可以将它们放在一起,不同的case表达式使用逗号分隔。
func SwitchExp() {
str := "hello"
switch str {
case "hello", "world":
fmt.Println("Hello,World!")
case "你好", "世界":
fmt.Println("你好,世界!")
}
}
分支表达式:switch 的 case 中不仅可以是值类型的常量判断,还可以是表达式等任意类型。这种方式类似于 else if
机制,一旦一个 case 表达式满足,后续 case 不再被判断而跳出整个 switch;但是可以使用 fallthrough
关键字强制执行后面的 case 代码块。
func SwitchExp() {
n := 10
switch {
case n > 9 && n < 20:
fmt.Println("9 < n < 20")
fallthrough
case n == 10:
fmt.Println("n == 10")
}
}
用于类型判断:switch 分支选择常被用来判断 Golang 中表示任意类型或空接口的 any/interface{}
变量中实际存储的变量类型。
func SwitchExp() {
var a interface{}
dataType(a)
var i int = 1
dataType(i)
var s string = "hello"
dataType(s)
}
func dataType(a any) {
switch t := a.(type) {
case nil:
fmt.Printf("变量的类型 :%T\r\n", t)
case int:
fmt.Println("变量是 int 型")
case float64:
fmt.Println("变量是 float64 型")
case func(int) float64:
fmt.Println("变量是 func(int) 型")
case bool, string:
fmt.Println("变量是 bool 或 string 型")
default:
fmt.Println("未知型")
}
}
/* output:
变量的类型 :<nil>
变量是 int 型
变量是 bool 或 string 型
*/
# 03 异步处理 select
待并发编程更新.......
# 参考资料
条件语句if · Go语言中文文档 (opens new window)