"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > Go语言如何动态发现导出包类型?

Go语言如何动态发现导出包类型?

2025-05-04에 게시되었습니다
검색:307

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.

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3