Go Switch

The switch statement in Go is a control structure used for selecting one block of code to execute from multiple options. Unlike some other programming languages such as C, C++, Java, JavaScript, and PHP, Go’s switch statement does not require a break statement to exit a case, as it automatically terminates after executing the matched case.

Tutorials dojo strip



Single-Case switch Syntax

Go

How It Works:

  1. The expression is evaluated once.
  2. The value of the expression is compared with the value in each case.
  3. If a match is found, the associated code block executes.
  4. The default block (optional) will execute if no case matches.




Example 1: Weekday Calculation

Go

Output (if day = 3):

Go




Example 2: Motorcycle Brand Selector

Go

Output (if model = "Ducati"):

Go




The default Keyword

The default keyword provides a fallback option when no case matches. For example:

Go

Output (if day = 10):

Go




Example 3: Type Check Error

Ensure all case values are of the same type as the switch expression. Mixing types will result in a compilation error. Here’s an illustration:

Go

Result:

Go
Tutorials dojo strip