Skip to main content
Module 6 · Lesson 3 of 528/50 in the course~10 min
Module lessons (3/5)

Type switch

Lesson preview5 hands-on exercises readyCourse Go · Module 6 — Interfaces

switch v := x.(type) { case int: ... } for dispatcher on runtime type.

What you'll learn in this lesson

  • Implement clean multi-type dispatchers with switch v := x.(type).
  • Expect static type narrowing of v within single-type case versus multi-type case (case int, float64:).
  • Also handle interfaces like fmt.Stringer and the case nil: case while avoiding limits on fallthrough.

Overview

When a function receives an interface like any and needs to handle several possible types, the special syntax switch v := x.(type) makes the code much cleaner than a chain of if/else with multiple type assertions.

In every case containing a only type, the variable v already automatically assumes that concrete type:

Sections covered in this lesson

  1. 1Basic syntax and automatic narrowing of v
  2. 2Cases with multiple types vs. interface-based cases
  3. 3Dispatch on structured errors and slices
  4. 4Guided practice
  5. 5Check for understanding
Pro Lesson · Module 6 — Interfaces

Unlock "Type switch" and the full Course Go curriculum

`switch v := x.(type) { case int: ... }` for dispatcher on runtime type.

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.