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

How Can I Discover All Exported Types in a Go Package at Runtime?

DDD
Release: 2025-01-05 21:04:45
Original
831 people have browsed it

How Can I Discover All Exported Types in a Go Package at Runtime?

Package Discoverability During Runtime

Unlike the reflect package, Go lacks a type discovery mechanism that allows for querying all types without knowing them explicitly. This raises the question:

Is there an alternative method to discover all exported types (structs in particular) in an active Go package?

One theoretical solution is a hypothetical function, "DiscoverTypes," that takes a package and returns all discovered types. However, this function does not exist within the reflect package.

Finding a Solution

In Go 1.5 and later, the newly introduced package types and importer provide a means to inspect binary and source packages. By utilizing the following code, you can discover all exported types within a package:

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)
    }
}
Copy after login

However, in versions prior to 1.5, the only reliable approach involves using the ast package to compile source code.

Real-World Use Case

This capability is especially useful in code generation utilities that identify and instantiate types meeting specific criteria. These utilities assist in generating test functions based on discovered types and reduce the need for manual code generation steps.

The above is the detailed content of How Can I Discover All Exported Types in a Go Package at Runtime?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template