In Go, types can be exported from a package to make them accessible to other packages. Sometimes, it may be necessary to access information about these exported types without directly importing the package. This article will explore how to get all defined types exported from a particular package using the go/importer package.
Question:
Consider the following demo package:
package demo type People struct { Name string Age uint } type UserInfo struct { Address string Hobby []string NickNage string }
In another package, how can we retrieve all the exported types from the demo package?
Answer:
To achieve this, we can use the go/importer package, which provides an API for importing packages and introspecting their contents. Here's how to do it:
import ( "fmt" "go/importer" ) func main() { pkg, err := importer.Default().Import("demo") if err != nil { fmt.Println("error:", err) return } for _, declName := range pkg.Scope().Names() { fmt.Println(declName) } }
In this code, we first import the demo package and then use the importer.Default().Import("demo") function to get the *Package representing the demo package.
Next, we iterate over the Names of the package's Scope, which contains the names of all the exported types in that package. These names are then printed to the standard output.
Note: When running this code in Go Playground, you will likely encounter an error. This is because the Go Playground's environment does not have the ability to retrieve package metadata from external sources.
The above is the detailed content of How Can I Retrieve All Exported Types from a Go Package Without Importing It?. For more information, please follow other related articles on the PHP Chinese website!