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

Type assertion

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

v, ok := i.(*MyT), the form with comma-ok to avoid panic, when preferring an assertion to the type switch.

What you'll learn in this lesson

  • Extract the concrete value or another interface from a variable of type interface with v, ok := x.(T).
  • Avoid panic at runtime by systematically using the safe form comma-ok instead of v := x.(T).
  • Distinguish *T and T in dynamic type controls and make feature detection towards optional interfaces (io.Closer).

Overview

An interface variable contains within it a pair (valore concreto, tipo dinamico). A type assertion allows you to verify or extract that underlying type.

You can assert an interface not only to a concrete struct, but also to another optional interface. It's a very common pattern in stdlib: _"if this object also implements io.Closer, close it when finished"_:

Sections covered in this lesson

  1. 1Safe form (comma ok) vs direct form at risk of panic
  2. 2Feature detection to another interface
  3. 3*T vs T: exact match
  4. 4Type assertion from map[string]any (dynamic JSON)
  5. 5Guided practice
  6. 6Check for understanding
Pro Lesson · Module 6 — Interfaces

Unlock "Type assertion" and the full Course Go curriculum

`v, ok := i.(*MyT)`, the form with comma-ok to avoid panic, when preferring an assertion to the type switch.

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.