Skip to main content
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 expr on multiple values and switch with no expression to replace long if/else if chains.
  • Take advantage of the automatic exit semantics for single case without risking accidental fallthroughs.
  • Combine init statement and case with 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

  1. 1Switch on multiple values and houses
  2. 2Expressionless switch: if / else if chain readable
  3. 3Init statement inside switch
  4. 4fallthrough explicit (and when to avoid it)
  5. 5Guided practice
  6. 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.