Go switch Statement

Go (Golang) – switch Statement

The switch statement in Go is a clean and powerful alternative to long if–else chains.
It improves readability and maintainability of code.


1️⃣ Basic switch Syntax

✔ No break needed (automatic break)


2️⃣ Example: Day of the Week


 


3️⃣ Multiple Values in One case


 


4️⃣ switch Without Expression

Works like an if–else if ladder.


 


5️⃣ switch with Short Statement

n is only available inside the switch.


6️⃣ fallthrough Keyword

Forces execution of the next case.


 

Output:

One
Two

⚠ Use carefully (no condition check in next case)


7️⃣ Type Switch

Used with interfaces to check data type.


 


8️⃣ switch vs if–else

Feature switch if–else
Readability High Medium
Multiple conditions Easy Complex
fallthrough Yes No
Type checking Yes No

Important Rules

✔ No parentheses needed
✔ Cases must be constant expressions
✔ Default is optional
✔ Automatic break

❌ Duplicate cases not allowed


Summary

  • switch simplifies complex conditions

  • No need for break

  • Supports multiple values and types

  • Cleaner than if–else

You may also like...