"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to dynamically discover export package types in Go language?

How to dynamically discover export package types in Go language?

Posted on 2025-05-04
Browse:745

How Can I Dynamically Discover Exported Package Types in Go?

Finding Exported Package Types Dynamically

In contrast to the limited type discovery capabilities in the reflect package, this article explores alternative methods for discovering all package types (particularly structs) at runtime.

Using types and importer (Go 1.5 and Later)

In Go 1.5 and subsequent versions, the types and importer packages introduce a powerful way to inspect packages. Here's how you can use them:

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

Using ast (Earlier Versions of Go)

Prior to version 1.5, the ast package can be utilized to parse and inspect source code for type discovery. However, this approach is more complex and may require additional parsing code.

Example Use Case

This type discovery capability can be used in various scenarios. For instance, in a code generation utility, it enables the identification of types that embed a specified type. This allows for the creation of test functions based on discovered types without requiring manual re-generation steps.

Conclusion

Despite the lack of native type discovery in the reflect package, Go provides alternative methods for examining package types at runtime. This allows for more flexible type introspection and can be leveraged in various applications, including code generation and testing frameworks.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3