Type assertions
Use type assertions when runtime type variation is real, and always handle the non-matching case deliberately.
Canonical guidance
- use the comma-ok form when failure is possible
- prefer type switches for multiple expected concrete types
- avoid interface plumbing that forces unnecessary assertions later
Use when
- boundary code with multiple concrete implementations
- decoding into interface-shaped values
- bridging plugin or handler registries
Avoid
- panic-prone assertions in ordinary code paths
- asserting types because APIs are too vague
- asserting through several layers of interfaces
Preferred pattern
if u, ok := v.(User); ok {
return u.ID
}
return ""
Anti-pattern
- relying on
v.(T)in normal control flow when a failed assertion is a valid possibility
Explanation: This anti-pattern is tempting because the syntax is short, but it turns a common branch into a runtime panic.
Why
- assertions are safe when the failure path is part of the design, not an afterthought
Related pages
Sources
- The Go Programming Language Specification - Go Team
- Go Data Structures: Interfaces - Russ Cox