Package Discoverability During Runtime
Unlike the reflect package, Go lacks a type discovery mechanism that allows for querying all types without knowing them explicitly. This raises the question:
Is there an alternative method to discover all exported types (structs in particular) in an active Go package?
One theoretical solution is a hypothetical function, "DiscoverTypes," that takes a package and returns all discovered types. However, this function does not exist within the reflect package.
Finding a Solution
In Go 1.5 and later, the newly introduced package types and importer provide a means to inspect binary and source packages. By utilizing the following code, you can discover all exported types within a package:
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) } }
However, in versions prior to 1.5, the only reliable approach involves using the ast package to compile source code.
Real-World Use Case
This capability is especially useful in code generation utilities that identify and instantiate types meeting specific criteria. These utilities assist in generating test functions based on discovered types and reduce the need for manual code generation steps.
The above is the detailed content of How Can I Discover All Exported Types in a Go Package at Runtime?. For more information, please follow other related articles on the PHP Chinese website!