Home >Backend Development >Golang >Can You Retrieve a `reflect.Type` in Go Without Instantiating the Type or Using its Name as a String?
Retrieving Reflect.Type from a Type or its Name in Go
This question explores whether it's possible to obtain the reflect.Type of a custom type, such as "t1" in the given example, without instantiating it or using its name as a string.
Regarding the first part of the question, yes, it's feasible to achieve this by using a typed nil. The following code snippet demonstrates this approach:
var v1 reflect.Type = reflect.TypeOf((*t1)(nil)).Elem()
In this example, we leverage a typed nil pointer to obtain the runtime type of "t1."
As for the second part, retrieving the reflect.Type directly from a type's name isn't supported in Go. The runtime doesn't maintain a map of all types in the current binary, which would be necessary to accomplish this.
While it's conceivable to create a type registry package and register types for lookup by string, this would inevitably be incomplete. Furthermore, anonymous types introduce complications as their names may not be unique.
While Go might theoretically offer a function to retrieve a type based on its name, it's unlikely that this feature will be implemented in the near future.
The above is the detailed content of Can You Retrieve a `reflect.Type` in Go Without Instantiating the Type or Using its Name as a String?. For more information, please follow other related articles on the PHP Chinese website!