Home >Backend Development >Golang >How Can I Discover Exported Types from External Go Packages?

How Can I Discover Exported Types from External Go Packages?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-30 05:40:09353browse

How Can I Discover Exported Types from External Go Packages?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn