Go Reflection
Reflection allows a Go program to inspect its own structure (types and values) at runtime. This is handled by the reflect package.
1. Type and Value
The two most important concepts are reflect.Type and reflect.Value.
2. Inspecting Structs
Reflection is commonly used to look inside structs, read their field names, and check their "tags."
3. Modifying Values
To modify a value through reflection, you must pass a pointer to the data and use Elem().
Why use Reflection?
- Generic Libraries: Packages like
encoding/jsonuse reflection because they don't know the type of your struct until the program is running. - Object Mapping: Libraries that map database rows to Go structs.
- Validation: Checking struct tags (e.g.,
validate:"required") at runtime.
Downsides
- Performance: Reflection is much slower than regular code.
- Type Safety: Reflection bypasses compile-time checks. If you try to set a
stringfield with anint, the program will panic at runtime. - Complexity: Reflection code is often harder to read and maintain.