Accessing Exported Types Across Packages
In Go, exported types are accessible by other packages. This allows for reuse and modularity in code design. However, how can you access all the defined exported types from a specific package?
Consider the following example:
package demo type People struct { Name string Age uint } type UserInfo struct { Address string Hobby []string NickNage string }
In a separate package, let's say,
import "demo"
From this other package, we seek to retrieve all exported types defined within the demo package. To achieve this, we can leverage the go/importer package:
package main import ( "fmt" "golang.org/x/tools/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) } }
This code imports the demo package using the importer and iterates over the defined names within its scope. The resulting output will list all exported types, in this case:
People UserInfo
However, it's worth noting that using this approach may result in an error on the Go Playground.
The above is the detailed content of How Can I Access All Exported Types from a Specific Go Package?. For more information, please follow other related articles on the PHP Chinese website!