Home >Backend Development >Golang >How Can I Discover Exported Types in a Running Go Package?

How Can I Discover Exported Types in a Running Go Package?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-15 14:26:16530browse

How Can I Discover Exported Types in a Running Go Package?

Using Runtime Package Discovery to Ascertain Package Types

The absence of a type discovery mechanism in the reflect package necessitates an alternate approach to discovering exported types, particularly structs, within a running Go package.

Solution in Go 1.5 and Later:

Leveraging the introduction of the types and importer packages in Go 1.5, it is possible to inspect binary and source packages. Consider the following example:

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)
    }
}

This code showcases the exploration of exported names within the "time" package using the importer package.

Pre-Go 1.5 Approach:

Prior to Go 1.5, the sole viable solution was to employ the ast package to compile source code. However, this approach entailed additional complexity.

The above is the detailed content of How Can I Discover Exported Types in a Running Go Package?. 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