Go switch Statement

Go Tutorial

 Go switch Statement – Complete Guide with Examples

In Go (Golang), the switch statement is a powerful and cleaner alternative to long if-else chains. It allows you to execute different blocks of code based on different conditions.

Go’s switch is more flexible and safer than in many other languages.

What Is a switch Statement in Go?

A switch statement checks a value or condition and executes the matching case.

Basic Syntax

  •  Easy to read
  •  No need for multiple if-else
  •  Automatically breaks after a match

 Simple Example of switch


 

Output

Wednesday
  •  Clean
  •  Readable

switch vs if-else

Using if-else

Using switch

Rule:
Use switch when checking multiple conditions on the same value.

 Multiple Values in a Single case

Go allows multiple values in one case.

  •  Reduces repetition
  •  Cleaner logic

switch Without an Expression (Very Important)

Go supports expression-less switch, which works like if-else.


 

  •  Powerful
  • Common in real-world Go code

switch with Short Statement

You can declare a variable inside switch.

  •  Scope limited to switch
  •  Clean and safe

fallthrough in Go

Unlike other languages, Go does not fall through by default.

Normal Behavior

Using fallthrough

Output

One
Two
  •  Use fallthrough carefully — it ignores the next case condition.

 Nested switch Statement

  •  Useful but avoid deep nesting

break in Go switch

break is rarely needed because Go automatically exits after a case.

  •  Included for loops or labeled breaks

default Case

The default case runs when no case matches.

  •  Optional but recommended

Common Mistakes

  •  Expecting automatic fallthrough
  • Forgetting default
  •  Overusing nested switches
  •  Using switch for complex logic
  •  Misusing fallthrough

 Best Practices

  •  Prefer switch over long if-else
  •  Avoid unnecessary fallthrough
  •  Use expression-less switch for conditions
  •  Keep cases simple
  •  Always consider default

 Interview Questions: Go switch

1. Does Go switch fall through by default?
No.

2. What is fallthrough?
It forces execution of the next case.

3. Can switch be used without an expression?
Yes.

4. Can multiple values be used in one case?
Yes.

5. Is break required in Go switch?
No.

 Summary

  •  Go switch is powerful and clean
  • No automatic fallthrough
  •  Supports multiple values per case
  •  Expression-less switch is flexible
  • Cleaner than if-else chains

Mastering the Go switch statement will help you write cleaner logic, readable code, and professional Go programs 🚀

You may also like...