golang中控制语句需要注意下面几个方面。
if 条件表达式 {
//执行代码块
}else if 条件表达式 {
//执行代码块
}else{
//执行代码块
}
- if后面一般不用小括号把条件包裹起来。不要多此一举。
- 大括号{}必须有。即使代码块只有一个语句也必须有大括号。
- golang可以在if语句的条件中,直接定义一个变量。如下:但是这个变量的作用域只在这个if条件内。判断的时候是最后一个语句age > 21起作用
func main() {
if age := 20;age > 21{
fmt.Println(age)
}else if age > 18 {
fmt.Println(age)
}
//fmt.Println(age) 错误:超出作用域
}
- else if 或 else 不能换行。如下:else if换行了,编译错误。这是golang强制要求代码风格一致。
if 条件表达式 {
}
else if 条件表达式 { //编译错误,不能换行。
}
golang的switch语句语法如下:可以使用break语句终止switch语句。
switch 值 {
case 值1,值2......:
//语句块
case 值3,值4......:
//语句块1
break
//语句块2
default:
//语句块
}
每个case分支不需要再加 break,默认每个都加上了break。
case/switch 后是一个表达式( 即:常量值、变量、一个有返回值的函数等都可以)。
case 后的各个表达式的值的数据类型,必须和 switch 的表达式数据类型一致。
case 后的值可以有多个,使用 逗号 间隔。
例子如下:将执行fmt.Println("语句5"),fmt.Println("语句6")
var num int = 5
switch num {
case 3,4:
fmt.Println("语句3")
fmt.Println("语句4")
case 5,6:
fmt.Println("语句5")
fmt.Println("语句6")
}
- case 后面的表达式如果是常量值(字面量),则要求不能重复。错误写法如下:
var num int = 5
switch num {
case 3,4:
fmt.Println("语句3")
fmt.Println("语句4")
case 4,6: //编译错误,以为上面case有4
fmt.Println("语句5")
fmt.Println("语句6")
}
- switch 后也可以不带表达式,类似 if --else 分支来使用。例子如下:
var num int = 5
switch {
case num > 6:
fmt.Println("语句1")
case num > 4:
fmt.Println("语句2") //输出:语句2
}
- switch 后也可以直接声明/定义一个变量,分号结束,不推荐。
switch num := 5; {
case num > 6:
fmt.Println("语句1")
case num > 4:
fmt.Println("语句2") //输出:语句2
}
- switch 穿透-fallthrough ,如果在 case 语句块后增加 fallthrough ,则会继续执行下一个 case,也叫 switch 穿透。例子如下:
var num int = 5
switch num {
case 5:
fmt.Println("语句1") //输出:语句1
fallthrough //默认只穿透一层
case 4:
fmt.Println("语句2") //输出:语句2
case 3:
fmt.Println("语句3")
}
执行完第一个case之后。遇到fallthrough 就会继续执行下一个case里面的语句块。不管下一个case是否匹配switch 后面的值。
- Type Switch:switch 语句还可以被用于 type-switch 来判断某个 interface 变量中实际指向的 变量类型。