Discovering Defined Types in External Packages
In Go, type definitions are exported when their names begin with uppercase letters. To access these types from another package, you can use the go/importer package.
Solution:
package main import ( "fmt" "go/importer" demo "example.com/path/to/demo" // import the package containing the types ) func main() { pkg, err := importer.Default().Import("example.com/path/to/demo") if err != nil { fmt.Println("error:", err) return } // Get the names of all exported types in the package for _, declName := range pkg.Scope().Names() { fmt.Println(declName) } }
This code will print the following output, which lists the names of the exported types defined in the demo package:
People UserInfo
Note: Using go/importer on the Go Playground may result in an error.
The above is the detailed content of How Can I Discover Exported Types from External Go Packages?. For more information, please follow other related articles on the PHP Chinese website!