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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete