caddyhttp: refactor to use reflect.TypeFor #7187
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
why you might use
reflect.TypeForinstead ofreflect.TypeOfin Go.Background
In Go, the
reflectpackage provides two similar-looking functions:reflect.TypeOf(x)Takes a value
xand returns itsreflect.Type.Example:
reflect.TypeFor[T]()(introduced in Go 1.22)A generic function that returns the
reflect.Typefor a type parameterTwithout needing a value.Example:
Why use
reflect.TypeForinstead ofreflect.TypeOf?No value needed
reflect.TypeOfrequires an actual value at runtime.If you only know the type (not a value), you have to create a dummy value:
reflect.TypeForworks directly with the type parameter:Compile-time type safety
reflect.TypeOf, the type is determined from a runtime value, so mistakes may only show up at runtime.reflect.TypeFor, the type is determined at compile time from the generic type parameter, so it’s safer and clearer.Better for generic code
Tbut no value of typeT.reflect.TypeOfcan’t be used without creating a zero value:reflect.TypeFor, you can simply do:Avoids unnecessary allocations
reflect.TypeOfmay allocate memory (especially for composite types).reflect.TypeForavoids this overhead entirely.Summary Table
reflect.TypeOfreflect.TypeFor(Go 1.22+)✅ Recommendation:
Use
reflect.TypeForwhen:Use
reflect.TypeOfwhen: