typeutil.go 849 B

123456789101112131415161718192021222324252627282930
  1. package typeutil
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. // TypeOf is a utility that can covert a T type to a package + type name for generic types.
  7. func TypeOf[T any]() string {
  8. var inst T
  9. var prefix string
  10. // get a reflect.Type of a variable with type T
  11. t := reflect.TypeOf(inst)
  12. // pointer types do not carry the adequate type information, so we need to extract the
  13. // underlying types until we reach the non-pointer type, we prepend a * each depth
  14. for t != nil && t.Kind() == reflect.Pointer {
  15. prefix += "*"
  16. t = t.Elem()
  17. }
  18. // this should not be possible, but in the event that it does, we want to be loud about it
  19. if t == nil {
  20. panic(fmt.Sprintf("Unable to generate a key for type: %+v", reflect.TypeOf(inst)))
  21. }
  22. // combine the prefix, package path, and the type name
  23. return fmt.Sprintf("%s%s/%s", prefix, t.PkgPath(), t.Name())
  24. }