Skip to content

Prefer reflect.TypeFor Has Fix

Description

Go 1.22 added reflect.TypeFor[T](), a direct way to obtain the reflect.Type for a type argument. It replaces the less readable nil-pointer expression reflect.TypeOf((*T)(nil)).Elem().

This is a syntactic rule: it assumes reflect names the standard-library package. Use it only when the module targets Go 1.22 or newer.

YAML

yaml
id: reflect-type-for
language: Go
rule:
  pattern: reflect.TypeOf((*$TYPE)(nil)).Elem()
fix: reflect.TypeFor[$TYPE]()

Example

go
import "reflect"

func typeOf[T any]() reflect.Type {
	return reflect.TypeOf((*T)(nil)).Elem()
}

Diff

go
import "reflect"

func typeOf[T any]() reflect.Type {
	return reflect.TypeOf((*T)(nil)).Elem() 
	return reflect.TypeFor[T]() 
}

Credits

Based on JetBrains' Go Modern Guidelines.

Made with ❤️ with Rust