Switch Statements in Go Programming Language
Switch Statement
Switch statements used to select one block of code out of many blocks for execution based on matched input.
Default block will execute if any of the cases are not match.
Example
package main
import
("fmt"
"time")
func main() {
today := time.Now()
fmt.Println("Today Date and Time:",today)
day :=15
// switch today.Day(){ or
switch day{
case 2:
fmt.Println("Today is 2nd, team changing day")
case 12:
fmt.Println("Today is 12th, team outing day")
case 15:
fmt.Println("Today is 15th, Independence day")
default:
fmt.Println("Today is Fun day")
}
}
You can execute this program live here https://onecompiler.com/go/3ut3ztyu5
Output
Today Date and Time: 2019-07-02 10:40:59.272224254 +0000 UTC m=+0.000192052
Today is 15th, Independence day
Switch Multiple Cases Statement
It is used to select same block of code for different cases.
Example
package main
import "fmt"
func main() {
var day = 10
day =30
switch day{
case 5,10,15:
fmt.Println("Today is holiday")
case 20,30,31:
fmt.Println("Today is party day")
case 6,8,12:
fmt.Println("Today is team outing day")
default:
fmt.Println("Today is fun day")
}
}
You can execute this program live here (https://onecompiler.com/go/3ut46qt5r)
Output
Today is party day
Switch fallthrough Statement
fallthrough keyword is used to force the execution flow to fall through the successive case block.
Example
package main
import (
"fmt"
)
func main() {
var number = 5
switch number {
case 5:
fmt.Println("This is 5th case block")
fallthrough
case 10:
fmt.Println("This is 10th case block ")
fallthrough
case 15:
fmt.Println("This is 15th case block")
fallthrough
case 25:
fmt.Println("This is 25th case block.")
case 31:
fmt.Println("This is 31st case block.")
default:
fmt.Println("No information available .")
}
}
You can execute this program live here https://onecompiler.com/go/3ut47akzh
Output
This is 5th case block
This is 10th case block
This is 15th case block
This is 25th case block.