Exposing Package Types at Runtime: A Methodological Exploration
While the reflect package offers comprehensive introspection capabilities, it requires prior knowledge of the target type or value. This presents a challenge for discovering all exported types, particularly structs, within a running package.
However, with the advent of Go 1.5, a new paradigm has emerged:
Using the types and importer Packages
In Go 1.5 and beyond, the types and importer packages provide a powerful mechanism for inspecting binary and source packages:
package main import ( "fmt" "go/importer" ) func main() { pkg, err := importer.Default().Import("time") if err != nil { fmt.Printf("error: %s\n", err.Error()) return } for _, declName := range pkg.Scope().Names() { fmt.Println(declName) } }
By iterating through the Scope() of the imported package, we can obtain a list of all exported identifiers, including type names. This provides a comprehensive view of the package's exposed types.
Pre-1.5 Solutions: Leveraging the ast Package
Before Go 1.5, the only reliable approach involved using the ast package to compile the source code and extract the desired information. This is a more complex and potentially error-prone method.
Application to Custom Type Discovery
The ability to discover package types at runtime is particularly useful in scenarios like the one you described: identifying and instantiating structs that embed a specified type. By leveraging the methods described above, you can automate this process and eliminate the need for manual updates or registration functions.
The above is the detailed content of How Can I Discover Exported Package Types at Runtime in Go?. For more information, please follow other related articles on the PHP Chinese website!