pprofGolangchannelwaitgroupswitch

一、switch的基本用法和场景

switchsiwtchifswitchswitchcaseifswitch
num1num2

代码:

  switch ch {
  case '+':
    res = num1 + num2
  case '-':
    res = num1 - num2
  case '*':
    res = num1 * num2
  case '/':
    if num2 == 0 {
      fmt.Println("nums2 is 0 and ch is /")
      break
    }
    res = num1 / num2
  default:
    fmt.Printf("err ch %c", ch)
  }
  fmt.Println(res)

二、switch俩个实用技巧

switchGolangcasebreakcasecaseC++casebreakswitchcaseswitch
Golang
1,1,+

输出

2
C++
1,1,+

输出

"err ch +"
2
switchfallthroughcasecasetrue

代码:

  switch mood {
  case "snow":
    fallthrough
  case "fine":
    fmt.Println("心情超好!")
  case "rainy":
    fallthrough
  case "overcast":
    fmt.Println("心情有点低落!")
  default:
    fmt.Printf("undefine mood %s", mood)
  }

输入:

snow

输出:

心情超好!

三、总结

switchififswitchswitchGolangswitchcasebreakswitchfallthrough