04 / 08

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

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.

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

Scenario Questions

0-2 years experience
  1. 1

    You'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. 2

    You 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. 1

    Our 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. 2

    We'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. 1

    Our 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. 2

    We'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. 1

    We 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. 2

    A 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?