Go 编程 | 07 - 条件和循环语句

一、if 条件控制语句

if 表达式 {
    // 表达式为 true 时执行的代码块
} else if 表达式2 {
    // 表达式为 true 时执行的代码块
} else if 表达式3 {
    // 表达式为 true 时执行的代码块
} else {
    // 表达式为 true 时执行的代码块
}
复制代码

需要注意的是 Go 中 if 控制语句的 { 不可以换行,必须要跟 if 关键字在同一行,否则会报错。

image.png

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 关键字后不能定义变量。

猜你喜欢

转载自juejin.im/post/7127680111565864973