Way to get type2 string representation for any reflect.Type

package main

import (
	"fmt"
	"reflect"

	"golang.org/x/sync/semaphore"
)

type Type[T any] struct{}

func PrintType[T any]() {
	type1 := reflect.TypeFor[T]().String()
	fmt.Println("type1", type1)

	type2 := reflect.TypeFor[Type[T]]().String()
	fmt.Println("type2", type2[10:len(type2)-1])

	fmt.Println()
}

func main() {
	PrintType[int]()
	// type1 int
	// type2 int

	PrintType[fmt.Formatter]()
	// type1 fmt.Formatter
	// type2 fmt.Formatter

	PrintType[semaphore.Weighted]()
	// type1 semaphore.Weighted
	// type2 golang.org/x/sync/semaphore.Weighted

	type Local struct{}
	PrintType[Local]()
	// type1 main.Local
	// type2 main.LocalĀ·1

	PrintType[func(Local) semaphore.Weighted]()
	// type1 func(main.Local) semaphore.Weighted
	// type2 func(main.LocalĀ·1) golang.org/x/sync/semaphore.Weighted
}

Need a way to get string type2 from any reflec.Type (not wraped in generic Type)

Or at least a way to extract type2 fields of a named struct, like

type Struct struct {
	Local
	semaphore.Weighted
}

Generic wrap hack not worked

type Type2[T any] struct{ _ T }

t := reflect.TypeFor[Type2[Struct]]().Field(0).Type

for fi := range t.NumField() {
	fmt.Println(t.Field(fi).Type.String())
}
// main.Local
// semaphore.Weighted

playground

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.