Skip to main content

Switch

  • 不用寫 break
  • fallthrough 用法:這個 case 做完,一併執行下個 case

Example

package main

import (
"fmt"
"time"
)

func main() {
// 一般用法
switch time.Now().Weekday() {
case time.Sunday:
fmt.Println("Today is Sunday")
case time.Saturday:
fmt.Println("Today is Saturday")
default:
fmt.Println("Today is weekday")
}

// 宣告變數寫法
switch hour := time.Now().Hour(); {
case hour > 20:
fmt.Println("> 20")
case hour <= 20:
fmt.Println("<= 20")
}

// fallthrough: 這個 case 做完,一併執行下個 case
// 會印出 2 3
number := 2
switch number {
case 1:
fmt.Println("1")
fallthrough
case 2:
fmt.Println("2")
fallthrough
case 3:
fmt.Println("3")
}
}