04 / 08

Explain type assertion and type switch with real-world examples.

Difficulty: 6/10
type assertion, type switch, interface{} handling

Type assertion extracts the concrete type from an interface value. A type switch checks multiple possible types in sequence, and is commonly used when handling JSON or errors.

Type assertion
Type switch — real-world middleware error handling

Real-world use: encoding/json unmarshals into interface{} where numbers become float64, objects become map[string]interface{}, and arrays become []interface{}. Type switches are essential for processing such dynamic data safely.

Scenario Questions

0-2 years experience

  1. 1You're given an interface{} that could be either a string or an int. How would you safely print its value without causing a panic?
  2. 2You have a function that returns interface{} and you know it's either []string or []int. How would you handle both cases without crashing?

2-5 years experience

  1. 1Our plugin system returns interface{} from different modules, and we're getting random panics in production when users upload malformed configs. How would you debug and fix this?
  2. 2We're unmarshaling JSON into a map[string]interface{} and need to extract nested values. When should you use type switches vs. nested type assertions, and why?

5-8 years experience

  1. 1Our API gateway receives dynamic payloads from 10+ upstream services, all returning interface{} with varying structures. How would you design the type dispatch layer for performance and maintainability?
  2. 2We're migrating from a hardcoded type handler to a plugin-based system using interface{}. What are the performance tradeoffs of type switches vs. reflection, and how would you benchmark them?

8+ years experience

  1. 1We have a legacy system using interface{} and type switches across 20+ microservices, and it's becoming a maintenance nightmare. How would you design a migration path to a more type-safe architecture without breaking clients?
  2. 2A cross-team service uses type switches to handle protocol variants from different vendors. How do you enforce consistency, avoid runtime surprises, and document expected types across teams?

Follow-up Questions

  • What happens if you assert a type that doesn't match and don't use the comma-ok idiom?
  • When would you prefer a type switch over a series of type assertions?
  • How would you debug a panic caused by an invalid type assertion in a production service?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.