0
0
Goprogramming~10 mins

Switch expression behavior in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Switch expression behavior
Start switch expression
Evaluate expression once
Compare expression to case values
Match found?
NoExecute default case if present
Execute matched case block
Exit switch
The switch expression is evaluated once, then compared to each case value in order. When a match is found, its block runs and the switch exits.
Execution Sample
Go
package main
import "fmt"
func main() {
  x := 2
  switch x {
  case 1: fmt.Println("One")
  case 2: fmt.Println("Two")
  default: fmt.Println("Other")
  }
}
This code checks the value of x and prints the matching case's message.
Execution Table
StepExpression ValueCase CheckedMatch?ActionOutput
12case 1NoSkip case 1
22case 2YesExecute case 2 blockTwo
32defaultSkippedSwitch exits after match
💡 Switch exits after executing the matched case block (case 2).
Variable Tracker
VariableStartAfter Step 1After Step 2Final
x2222
Key Moments - 2 Insights
Why does the switch stop after matching case 2 and not check the default case?
Because once a matching case is found (step 2 in execution_table), the switch executes that case block and exits immediately without checking further cases.
Is the switch expression evaluated multiple times for each case?
No, the expression is evaluated once at the start (step 1), then compared to each case value.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at step 2?
AOne
BOther
CTwo
DNo output
💡 Hint
Check the 'Output' column for step 2 in the execution_table.
At which step does the switch expression get evaluated?
AStep 1
BStep 2
CStep 3
DIt is evaluated multiple times
💡 Hint
Look at the 'Expression Value' column in the execution_table.
If x was 3, which case would execute according to the execution_table logic?
Acase 1
Bdefault
Ccase 2
DNo case executes
💡 Hint
Recall that if no case matches, the default case runs.
Concept Snapshot
switch expression {
  case value1:
    // runs if expression == value1
  case value2:
    // runs if expression == value2
  default:
    // runs if no case matches
}

- Expression evaluated once
- Cases checked in order
- Executes first matching case and exits
- Default runs if no match
Full Transcript
In Go, a switch expression is evaluated once at the start. Then, each case is checked in order to see if it matches the expression's value. When a match is found, the corresponding case block runs and the switch exits immediately. If no case matches, the default block runs if it exists. For example, if x equals 2, the switch checks case 1 (no match), then case 2 (match), runs that block, and stops without checking default. This behavior helps write clear multi-way decisions without repeated expression evaluation.