Display the type of a generic type

Is there a way to display the type of a generic type?

I know you can create a dummy value of the generic type and then use %T format specifier to get the type:

package main

import (
	"fmt"
)

func displayType[T any]() {
	var data T//Create a dummy value
	fmt.Printf("The type is %T\n", data)
}

func main() {
	displayType[string]()
	displayType[int]()
	displayType[[]int]()
}

Is there a way to display the type of a generic type without using a dummy value?

package main

import (
	"fmt"
)

func displayType[T any]() {
//What can we do here to display the generic type T without the dummy value?
}

func main() {
	displayType[string]()
	displayType[int]()
	displayType[[]int]()
}

I think that fmt.Printf() was primarily designed for printing information about values and thus cannot inspect types without an instantation.

1 Like

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