Go语言Switch的用法

Go语言Switch的用法

1、等值匹配

package main

import "fmt"

func f(a, b int, op string) int {
   switch op {
   case "+":
      return a + b
   case "-":
      return a - b
   case "*":
      return a * b
   case "/":
      return a / b
   default:
      panic("传入的不是加减乘除(+-*/)运算符")

   }

}
func main() {
   fmt.Println(f(1, 5, "+"))
   fmt.Println(f(1, 5, "-"))
   fmt.Println(f(1, 5, "*"))
   fmt.Println(f(1, 5, "/"))
   fmt.Println(f(1, 5, "no"))
}

2、根据条件匹配

package main

func f(a int) {
   switch {
   case a > 80:
      print("A")
   case a > 60:
      print("B")
   case a > 30:
      print("C")
   case a > 10:
      print("D")
   default:
      print("E")
   }

}
func main() {
   f(98)
   f(68)
   f(39)
   f(20)
   f(8)
}

提示:case块不用添加break语句,默认会break,如果想要继续执行,手动添加fallthrough,例如

package main

func f(a int) {
   switch {
   case a > 80:
      print("A")
      fallthrough
   case a > 60:
      print("B")
   case a > 30:
      print("C")
   case a > 10:
      print("D")
   default:
      print("E")
   }

}
func main() {
   f(98)
}
posted @ 2022-06-11 20:12  南风丶轻语  阅读(84)  评论(0编辑  收藏  举报