Go Language - Switch Statement

A switch statement is a shorter way to write a sequence of if-else statements. It runs the first case whose value is equal to the condition expression. The cases are evaluated from top to bottom, stopping when a case succeeds. If no case matches and there is a default case, its statements are executed.

Example 1:

package main

import "fmt"

func main() {

day := 6

switch day {
case 1:
fmt.Println("Sunday")
case 2:
fmt.Println("Monday")
case 3:
fmt.Println("Tuesday")
case 4:
fmt.Println("Wednesday")
case 5:
fmt.Println("Thursday")
case 6:
fmt.Println("Friday")
case 7:
fmt.Println("Saturday")
}
}

Output:




Example 2: break breaks the inner switch

package main

import "fmt"

func main() {

loop:
for i := 0; i < 9; i++ {
fmt.Printf("%d", i)
switch {
case i == 1:
fmt.Println("start")

case i == 8:
fmt.Println("end")

case i == 6:
fmt.Println("stop")
break loop

case i > 3:
fmt.Println("sleeping..")
break

default:
fmt.Println("default..")
}
}
}

Output:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example