Home > Article > Backend Development > Can You Get a `reflect.Type` from a String Name in Go?
Consider the following task:
type t1 struct { i int; s string }
How can you obtain the reflect.Type of t1 without instantiating it?
Yes, it's possible:
var v1 reflect.Type = reflect.TypeOf((*t1)(nil)).Elem()
You can use reflect.TypeOf to get the reflect.Type of a pointer to a nil struct of type t1, and then use Elem to get the type of the underlying struct.
Unfortunately, no. Go does not maintain a map of types in the current binary, making it impractical to retrieve a type from a string. While it is possible to create a custom type registry package, it would be incomplete and potentially ambiguous due to anonymous types and name collisions.
The above is the detailed content of Can You Get a `reflect.Type` from a String Name in Go?. For more information, please follow other related articles on the PHP Chinese website!