Go switch Statement

beginner
22 min

Go switch Statement

Welcome to our deep dive into the switch statement in Go! This powerful construct will help you manage multiple conditions with ease. Let's get started! 🎯

What is a switch statement?

The switch statement is a control structure that allows you to test the value of an expression against multiple cases. It's particularly useful when you need to evaluate numerous alternatives based on a single variable. 💡

Syntax

Here's the basic structure of a switch statement:

go
switch expression { case constant1: // statements case constant2: // statements ... default: // default statements }

The expression, which can be a variable, is tested against the constants. If a match is found, the associated statements will be executed. If no case matches, the default block is executed.

Example

Let's take a look at a simple example:

go
package main import "fmt" func main() { day := "Monday" switch day { case "Monday": fmt.Println("Start of the week!") case "Friday": fmt.Println("Countdown to the weekend!") default: fmt.Println("Just another day!") } }

In this example, we have a variable day set to "Monday". The switch statement tests this value against three cases. When "Monday" is found, the corresponding statement ("Start of the week!") is executed.

Advanced Example

Let's take it up a notch by creating a simple calculator:

go
package main import "fmt" func main() { operation := "+" num1 := 5 num2 := 3 switch operation { case "+": fmt.Println(num1 + num2) case "-": fmt.Println(num1 - num2) case "*": fmt.Println(num1 * num2) case "/": fmt.Println(num1 / num2) default: fmt.Println("Invalid operation!") } }

In this example, we have an operation variable that can take the values of "+", "-", "*", or "/". Depending on the operation, the calculator performs the corresponding operation and prints the result. If an invalid operation is given, the default case is executed.

Practice Time

Quick Quiz
Question 1 of 1

Which case will be executed for `day = "Tuesday"` in the following code?

That's it for today! We've covered the basics of the switch statement in Go. In the next lesson, we'll explore how to use the switch statement with strings and ranges. Keep coding and enjoy the learning journey! 📝 ✅