Go - Switch Case Example

1. Introduction

The switch statement in Go provides an efficient way to dispatch execution to different parts of code based on the value of an expression. Unlike in some other languages, Go's switch cases do not need explicit break statements. This blog post will illustrate the usage of switch and case in Go with an example.

Definition

A switch statement is a type of conditional statement that evaluates an expression and compares it against multiple possible cases. When a case matches the expression, the code associated with that case is executed. In Go, the switch statement automatically breaks at the end of a case unless it ends with a fallthrough statement.

2. Program Steps

1. Define a variable for the switch expression.

2. Write a switch statement with several case clauses to match the variable's value.

3. Include a default clause to handle cases where none of the case clauses match.

4. Optionally, demonstrate the use of fallthrough in a case clause.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Define a day variable
	day := "Wednesday"

	// Step 2: Write a switch statement to print a message based on the day
	switch day {
	case "Monday":
		fmt.Println("It's Monday, the week has just begun.")
	case "Tuesday":
		fmt.Println("It's Tuesday, let's get into the groove.")
	case "Wednesday":
		fmt.Println("It's Wednesday, half way through the week!")
	case "Thursday":
		// Step 4: Demonstrate fallthrough
		fmt.Println("It's Thursday, almost there.")
		fallthrough
	case "Friday":
		fmt.Println("It's Friday, the weekend is near!")
	case "Saturday", "Sunday":
		fmt.Println("It's the weekend, time to relax!")
	default:
		// Step 3: Default case when none of the cases match
		fmt.Println("That's not a day of the week!")
	}
}

Output:

It's Wednesday, half way through the week!

Explanation:

1. package main - Defines the package name for the Go program.

2. import "fmt" - Imports the Format package for formatted I/O.

3. day := "Wednesday" - Initializes a string variable day with the value "Wednesday".

4. switch day {...} - A switch statement is started to evaluate the value of day.

5. case "Monday", case "Tuesday", ..., case "Wednesday": - Several case clauses are defined, each checking for a match with the value of day.

6. When day matches "Wednesday", the associated fmt.Println statement executes, printing out a message.

7. The default clause is used to handle any case where day does not match any of the defined case values.

8. The output shows the message for "Wednesday", confirming that the switch statement correctly identified the matching case.

9. The fallthrough keyword is used in the "Thursday" case to indicate that the following case ("Friday") should also be executed if "Thursday" matches. However, it's not demonstrated in the output since day is set to "Wednesday".


Comments