Fix typeName panic for interface type parameters
reflect.TypeOf on a nil interface value returns nil, causing a panic when Kind() is called. Use reflect.TypeFor[T]() instead, which resolves the type directly from the type parameter. Signed-off-by: Bryan Frimin <bryan@getprobo.com>
This commit is contained in:
@@ -69,8 +69,7 @@ func RunTyped[T any](
|
|||||||
}
|
}
|
||||||
|
|
||||||
func typeName[T any]() string {
|
func typeName[T any]() string {
|
||||||
var zero T
|
t := reflect.TypeFor[T]()
|
||||||
t := reflect.TypeOf(zero)
|
|
||||||
if t.Kind() == reflect.Pointer {
|
if t.Kind() == reflect.Pointer {
|
||||||
t = t.Elem()
|
t = t.Elem()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -120,6 +120,24 @@ func TestTypeName(t *testing.T) {
|
|||||||
assert.Equal(t, "status", typeName[Status]())
|
assert.Equal(t, "status", typeName[Status]())
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
t.Run(
|
||||||
|
"any interface returns output",
|
||||||
|
func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert.Equal(t, "output", typeName[any]())
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
t.Run(
|
||||||
|
"named interface returns lowercased name",
|
||||||
|
func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
assert.Equal(t, "error", typeName[error]())
|
||||||
|
},
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRunTyped(t *testing.T) {
|
func TestRunTyped(t *testing.T) {
|
||||||
|
|||||||
Reference in New Issue
Block a user