When to Avoid Reflection in Go

Avoid Go reflection for performance-critical code or when static typing is possible, as it is slower and less safe than direct type access.

Avoid reflection in Go when you need maximum performance, type safety, or when the compiler can optimize static types away. Reflection is significantly slower than direct type access and prevents the compiler from inlining or optimizing code paths. Use it only for generic libraries, serialization, or frameworks where static typing is impossible.

// Avoid: Slow, unsafe, no compile-time checks
func GetValue(i interface{}) any {
    return reflect.ValueOf(i).Field(0).Interface()
}

// Prefer: Fast, safe, optimized
func GetValue(s MyStruct) string {
    return s.Name
}