What Is Reflection in Go and When to Use It

Reflection in Go allows runtime inspection and modification of types via the reflect package, ideal for generic libraries but costly for performance.

Reflection in Go is the ability of a program to inspect and modify its own structure and behavior at runtime using the reflect package. Use it when you need to write generic code that handles unknown types, such as serialization libraries, dependency injection frameworks, or debugging tools, but avoid it for performance-critical paths due to its overhead.

package main

import (
	"fmt"
	"reflect"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	p := Person{Name: "Alice", Age: 30}
	v := reflect.ValueOf(p)
	t := v.Type()

	fmt.Printf("Type: %s\n", t.Name())
	for i := 0; i < v.NumField(); i++ {
		fmt.Printf("Field %s: %v\n", t.Field(i).Name, v.Field(i))
	}
}