Home > Backend Development > Golang > Can You Get a `reflect.Type` from a String Name in Go?

Can You Get a `reflect.Type` from a String Name in Go?

Linda Hamilton
Release: 2024-11-09 06:08:02
Original
1042 people have browsed it

Can You Get a `reflect.Type` from a String Name in Go?

Getting reflect.Type from Type 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?

  • Can you get the reflect.Type without instantiation?

Yes, it's possible:

var v1 reflect.Type = reflect.TypeOf((*t1)(nil)).Elem()
Copy after login

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.

  • Can you get the reflect.Type from the string name "t1"?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template