Module lessons (2/5)
Type assertion
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
panicat runtime by systematically using the safe form comma-ok instead ofv := x.(T). - Distinguish
*TandTin 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
- 1Safe form (
comma ok) vs direct form at risk of panic - 2Feature detection to another interface
- 3
*TvsT: exact match - 4Type assertion from
map[string]any(dynamic JSON) - 5Guided practice
- 6Check for understanding
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.