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:

Comments

Popular posts from this blog

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

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

Java - Blowfish Encryption and decryption Example

Java - DES Encryption and Decryption example

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

ReactJS - Bootstrap - Buttons

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Top 5 Java ORM tools - 2024

Java - How to Count the Number of Occurrences of Substring in a String