Programming Languages
Go
Subjective
Oct 04, 2025
What is reflection in Go and how is it used?
Detailed Explanation
Reflection in Go:
• Runtime type inspection and manipulation
• reflect package provides functionality
• Type and Value are main types
• Performance overhead
• Used in JSON marshaling, ORMs, etc.
Example:
func inspect(x interface{}) {
v := reflect.ValueOf(x)
t := reflect.TypeOf(x)
fmt.Printf("Type: %v\n", t)
fmt.Printf("Value: %v\n", v)
if v.Kind() == reflect.Struct {
for i := 0; i < v.NumField(); i++ {
field := t.Field(i)
value := v.Field(i)
fmt.Printf("%s: %v\n", field.Name, value)
}
}
}
Use cases:
• Serialization/deserialization
• Dependency injection
• Generic programming (pre-generics)
• Testing frameworks
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts