1. if
在Go中,if语法有以下几个特点需要注意
- 可以省略条件表达式的括号
- 初始化语句可以定义代码块局部变量
- 代码块左括号必须在条件表达式尾部
- 不支持类似PHP中的三目运算符
// if条件语句格式如下:
if 布尔表达式 {
// 代码块
}
if str := "abc";i > 0 {
fmt.Println(str[0])
} else if i < 0 {
fmt.Println(str[1])
} else {
fmt.Println(str[2])
}
2. switch
- switch用于不同条件执行不同的业务逻辑,每一个唯一的case分支都是唯一的,由上至下逐一匹配,直到成功为止,在Go中条件表达可以是任意类型,不限于常量,可省略break,默认自动终止
- switch也可用于type类型检查,用来判断某个interface变量中实际存储的变量类型
- switch不写条件的时候当if与else运用
func main() {
var i string
i = "Mossil"
getTypes(i)
//省略条件表达式,可当 if...else if...else
var n = 0
switch {
case n > 0 && n < 10:
fmt.Println("i > 0 and i < 10")
case n > 10 && n < 20:
fmt.Println("i > 10 and i < 20")
default:
fmt.Println("def")
}
}
// switch判断类型
func getTypes(i interface{}) {
switch i.(type) {
case nil:
fmt.Println("i的类型是nil\n")
case int:
fmt.Println("i的类型是int\n")
case string:
fmt.Println("i的类型是string\n")
case bool:
fmt.Println("i的类型是bool\n")
}
}
3. fallthrough
- 可以使用fallthrough强制执行后面的case代码
Go语言控制流详解

被折叠的 条评论
为什么被折叠?



