Module 2 · Lesson 4 of 59/50 in the course~10 min
Module lessons (4/5)
idiomatic switch
Lesson preview5 hands-on exercises readyCourse Go · Module 2 — Flow Control
No implicit fallthrough, complex expressions in cases, unconditional switches as if chains.
What you'll learn in this lesson
- Choose between
switch expron multiple values andswitchwith no expression to replace longif/else ifchains. - Take advantage of the automatic exit semantics for single
casewithout risking accidental fallthroughs. - Combine init statement and
casewith multiple values separated by commas.
Overview
In Go the switch is much more flexible and secure than in C/Java: there is no implicit fallthrough between one case and the next, so you never risk bugs from forgotten break.
A single case can list multiple values separated by commas, and exit at the end of its block automatically:
Sections covered in this lesson
- 1Switch on multiple values and houses
- 2Expressionless switch:
if / else ifchain readable - 3Init statement inside
switch - 4
fallthroughexplicit (and when to avoid it) - 5Guided practice
- 6Check for understanding
Pro Lesson · Module 2 — Flow Control
Unlock "idiomatic switch" and the full Course Go curriculum
No implicit fallthrough, complex expressions in cases, unconditional switches as if chains.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Go plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.