0
0
Goprogramming~5 mins

Switch statement in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a switch statement in Go?
A switch statement in Go lets you choose between many options based on the value of an expression. It is like asking multiple questions and picking the answer that matches.
Click to reveal answer
beginner
How do you write a basic switch statement in Go?
Use the keyword switch followed by a value. Then write case for each option and default for when no case matches. Example:<br>
switch x {
case 1:
  // do something
case 2:
  // do something else
default:
  // fallback
}
Click to reveal answer
beginner
What happens if no case matches and there is no default in a Go switch?
The switch does nothing and the program continues after the switch block. No code inside the switch runs.
Click to reveal answer
intermediate
Can a Go switch statement have multiple values in one case?
Yes! You can list multiple values separated by commas in one case. For example:<br>
switch day {
case "Saturday", "Sunday":
  fmt.Println("Weekend")
default:
  fmt.Println("Weekday")
}
Click to reveal answer
intermediate
How does Go switch differ from if-else chains?
Go switch is cleaner and easier to read when checking one value against many options. It also stops checking after the first match without needing breaks, unlike some other languages.
Click to reveal answer
What keyword starts a switch statement in Go?
Aswitch
Bcase
Cselect
Dif
What happens if no case matches and there is no default case?
AThe switch block is skipped
BAn error is shown
CThe first case runs anyway
DThe program crashes
How do you write multiple values in one case?
AWrite multiple case statements
BUse the OR operator (||)
CUse semicolons between values
DSeparate values with commas
Does Go switch require break statements to stop after a case?
AOnly if you want to skip cases
BYes, always
CNo, it stops automatically
DOnly in default case
Which of these is a valid switch statement header in Go?
Aswitch x then {
Bswitch x {
Cswitch (x) {
Dswitch on x {
Explain how a switch statement works in Go and how it differs from if-else.
Think about how Go picks one matching case and stops.
You got /5 concepts.
    Write a simple Go switch statement that prints "Weekend" for Saturday and Sunday, and "Weekday" for other days.
    Use commas to list Saturday and Sunday in one case.
    You got /4 concepts.