proposal: reflect: add generic variants of
The current implementations of
var ex fmt.Stringer t := reflect.TypeOf(ex) // Results in the underlying type, not fmt.Stringer itself. p := reflect.TypeOf(&ex).Elem() // Results in fmt.Stringer itself.
This problem is exacerbated in the case where the value in question is from a non-addressable source, such as a function return, requiring an extra variable just to be able to address the interface type.
This is not true for generic functions, however. As such, I propose adding two new functions which I will call
func GenericTypeOf[T any](v T) reflect.Type func GenericValueOf[T any](v T) reflect.Value
These functions behave exactly as the existing two do, but with the difference that when passed a value of an interface type, they operate directly on the compile-time interface type, rather than the underlying runtime type.
As an aside, a
The text was updated successfully, but these errors were encountered:
Perhaps not. I know that I found the behavior of the existing functions around interfaces somewhat confusing when I was first getting started with Go, and I'm sure that someone else has as well. Also, as I mentioned, the examples in the proposal are some of the simpler cases to work around, but cases where the values aren't addressable are slightly more awkward.
Edit: While it's quite possible to implement this functionality externally (
It's maybe not the common case, but for
Speaking for myself, I need to do that every time I want to compare a reflected-on type with some known
With regard to
So with respect to this proposal, I support only the variant suggested in the addendum of the proposal description. I've already been defining this function myself and found it pleasant and clear to use:
For the record, another function I've found useful has been this one:
This avoids the awkwardness needed to extract a reflect.Value
A suitable spelling for the
Some possibilities and their drawbacks:
I'm not entirely sure it would help much. In my experience, reflect.ValueOf is most often called on a value of interface type, and in that case, the value returned by a generic version of reflect.ValueOf would always have a Type.Kind of Interface, and so in practice you'd just end up calling IsNil to check if it's OK to call Elem (because you're almost always interested in what's going on inside the interface value that's passed to ValueOf), which I think amounts to much the same thing in the end as checking for nil on the original interface value.