一、if 条件控制句子
if 表达式 { // 表达式为 true 时履行的代码块 } else if 表达式2 { // 表达式为 true 时履行的代码块 } else if 表达式3 { // 表达式为 true 时履行的代码块 } else { // 表达式为 true 时履行的代码块 }
需求留意的是 Go 中 if 控制句子的 {
不能够换行,必须要跟 if 要害字在同一行,不然会报错。

func main() { age := 3 if age > 60 { fmt.Println("晚年了") } else if age > 40 { fmt.Println("中年了") } else if age > 18 { fmt.Println("青年了") } else if age > 5 { fmt.Println("少年了") } else if age > 0 { fmt.Println("婴幼儿") } else { fmt.Println("输入过错") } }
Go 中 if 句子支撑在条件表达式中界说变量
func main() { // 变量界说在 if 条件表达式中 if age := 3; age > 60 { fmt.Println("晚年了") } else if age > 40 { // 其余代码不变 } }
在 if 条件表达式中界说的局部变量就只能在 if 代码块中运用。
二、switch 句子
switch 句子用于依据不同的条件履行不同的动作,if 条件句子的判别大多是范围的判别,如果条件表达式是一个详细的值,那么更适合运用 switch 句子来完成依据不同的值履行不同的操作
switch var { case val1: // 履行的操作 case val2: // 履行的操作 case val3: // 履行的操作 default: // 默认履行的操作 }
func main() { seasonEnum := 2 switch seasonEnum { case 1: fmt.Println("春天") case 2: fmt.Println("夏天") case 3: fmt.Println("秋天") case 4: fmt.Println("冬季") default: fmt.Println("输入过错") } }
case 要害字后边也能够写多个值,多个值之间运用 ,
离隔,当满足列出的任何一个值时都会往下履行
func main() { month := 4 switch month { case 1, 3, 5, 7, 8, 10, 12: fmt.Println("这个月份有 31 天") case 4, 6, 9, 11: fmt.Println("这个月份有 30 天") case 2: fmt.Println("这个月有 28 天或许 29 天") default: fmt.Println("输入过错") } }
履行上述代码,输出成果如下:
这个月份有 30 天
switch 句子也能够像 if 句子一样对表达式进行判别,然后依据判别成果选择要履行的分支
func main() { age := 10 switch { case age > 60: fmt.Println("退休了") case age > 23: fmt.Println("工作了") default: fmt.Println("好好学习") } }
履行上述代码,输出成果如下:
好好学习
case 要害字后不能界说变量。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)