0
0
Goprogramming~10 mins

Switch statement in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Switch statement
Start
Evaluate expression
Compare with case 1?
NoCompare with case 2?
Execute case 1
Exit switch statement
The switch statement evaluates an expression once and compares it to each case value in order. When a match is found, it executes that case's code and then exits the switch.
Execution Sample
Go
package main
import "fmt"
func main() {
  day := 3
  switch day {
  case 1: fmt.Println("Monday")
  case 2: fmt.Println("Tuesday")
  case 3: fmt.Println("Wednesday")
  default: fmt.Println("Unknown day")
  }
}
This code checks the value of 'day' and prints the matching weekday name or 'Unknown day' if no match.
Execution Table
StepExpression ValueCase CheckedMatch?ActionOutput
13case 1NoCheck next case
23case 2NoCheck next case
33case 3YesExecute case 3Wednesday
4---Exit switch
💡 After matching case 3, switch exits without checking further cases.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
day33333
Key Moments - 2 Insights
Why does the switch stop checking cases after finding a match?
In the execution_table at Step 3, once case 3 matches, the switch executes that case and immediately exits, so no further cases are checked.
What happens if no case matches the expression value?
If no case matches, the default case runs as a fallback. In this example, default would print 'Unknown day' if day was not 1, 2, or 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at Step 3?
A"Tuesday"
B"Monday"
C"Wednesday"
D"Unknown day"
💡 Hint
Check the Output column at Step 3 in the execution_table.
At which step does the switch statement stop checking further cases?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the Match? and Action columns in the execution_table to see when a case matches and switch exits.
If day was 5, which case would run according to the execution flow?
Acase 3
Bdefault
Ccase 1
DNo case runs
💡 Hint
Recall that default runs when no case matches; see key_moments about default case.
Concept Snapshot
switch expression {
  case value1:
    // code
  case value2:
    // code
  default:
    // code
}

- Evaluates expression once
- Compares to each case in order
- Executes first matching case
- Exits switch after match
- default runs if no match
Full Transcript
The switch statement in Go evaluates an expression once and compares it to each case value in order. When a case matches, it executes that case's code and then exits the switch without checking further cases. If no case matches, the default case runs as a fallback. In the example, the variable 'day' is 3, so the switch checks case 1 (no match), case 2 (no match), then case 3 (match), prints 'Wednesday', and exits. This behavior helps avoid writing multiple if-else statements and makes code clearer when checking one value against many possibilities.