Go switch Statement

Introduction

Go switch statement can run one of many blocks of code by matching a value.

package main // ww w .  j a va 2s  . c o  m

import (
  "fmt"
  "time"
)

func main() {
  today := time.Now()

  switch today.Day() {
  case 5:
    fmt.Println("5th.")
  case 10:
    fmt.Println("10th.")
  case 15:
    fmt.Println("15th.")
  case 25:
    fmt.Println("25th.")
  case 31:
    fmt.Println("31st.")
  default:
    fmt.Println("default.")
  }
}

The default statement is executed in case of no matching.

Go Switch Statement with multiple case values

package main //from www. j av a2  s .  c  om

import (
  "fmt"
  "time"
)
func main() {
  today := time.Now()
  var t int = today.Day()

  switch t {
  case 5, 10, 15:
    fmt.Println("Clean your house.")
  case 25, 26, 27:
    fmt.Println("Buy some food.")
  case 31:
    fmt.Println("Party tonight.")
  default:
    fmt.Println("No information available for that day.")
  }
}

Go Switch fallthrough keyword can force the execution flow to fall through the next case block.

package main //from   w  w w . j  ava2s.co m

import (
  "fmt"
  "time"
)

func main() {
  today := time.Now()

  switch today.Day() {
  case 5:
    fmt.Println("5.")
    fallthrough
  case 10:
    fmt.Println("10.")
    fallthrough
  case 15:
    fmt.Println("15.")
    fallthrough
  case 25:
    fmt.Println("25.")
    fallthrough
  case 31:
    fmt.Println("31.")
  default:
    fmt.Println("default.")
  }
}

Go switch statement can have an initialization statement to declare variables local to the switch code block.

package main /*from w  w w  . ja v a 2 s  . c  o  m*/

import (
  "fmt"
  "time"
)

func main() {
  switch today := time.Now(); {
      case today.Day() < 5:
        fmt.Println("less than 5.")
      case today.Day() <= 10:
        fmt.Println("less and equal than 10.")
      case today.Day() > 15:
        fmt.Println("greater than 15.")
      case today.Day() == 25:
        fmt.Println("is 25.")
      default:
        fmt.Println("default.")
  }
}

Go Switch Statement with conditional operators

Go switch case statement can use conditional operators.

package main //www.  jav  a 2s.co m

import (
  "fmt"
  "time"
)

func main() {
  today := time.Now()

  switch {
  case today.Day() < 5:
    fmt.Println("less than 5.")
  case today.Day() <= 10:
    fmt.Println("less and equal than 10.")
  case today.Day() > 15:
    fmt.Println("greater than 15.")
  case today.Day() == 25:
    fmt.Println("is 25.")
  default:
    fmt.Println("default.")
  }
}



PreviousNext

Related