reflect package implements run-time reflection, allowing a program to manipulate objects with arbitrary types.
Basic Reflection
Type Information
Modifying Values
Struct Field Access
Method Calls
Creating Values
Practical Examples
JSON-like Marshal
Generic Copy Function
Struct to Map
Kind Values
Best Practices
- Use sparingly - Reflection is slow and loses type safety
- Check CanSet() - Before modifying values
- Handle panics - Reflection can panic on invalid operations
- Cache Type info - Don’t reflect in hot paths
- Prefer interfaces - When possible, use interface methods
- Document usage - Reflection code is hard to understand