The reflect package inspects types and values at runtime—powerful but slower and less clear than generics or code generation. Used in JSON, ORM-like tools, and dependency injection frameworks.
Basic reflect
v := reflect.ValueOf(x)
t := reflect.TypeOf(x)
fmt.Println(t.Kind(), v.Interface())
Values must be addressable to mutate via reflection. Prefer compile-time types when possible—reflection is last resort.
Important interview questions and answers
- Q: When avoid reflection?
A: Hot paths, simple APIs, when generics or interfaces suffice. - Q: reflect vs generics?
A: Generics give compile-time safety; reflection trades performance for flexibility.
Self-check
- Which package provides TypeOf and ValueOf?
- Why is reflection slower?
Tip: Prefer generics or code generation over reflection in hot paths—reflection is for frameworks and one-off tooling.
Interview prep
- When avoid reflection?
Hot paths and simple APIs—prefer compile-time types or generics.
- reflect performance?
Slower and less clear—runtime type inspection has overhead.