How to get all defined types?

前端 未结 4 1152
我在风中等你
我在风中等你 2020-12-21 03:10
package demo

type People struct {
    Name string
    Age  uint
}

type UserInfo struct {
    Address  string
    Hobby           


        
相关标签:
4条回答
  • 2020-12-21 04:11

    Drat, I was hoping that Jsor's answer was wrong, but I can't find any way to do it.

    All is not lost though: If you have the source to 'demo', you could use the parser package to fish out the information you need. A bit of a hack though.

    0 讨论(0)
  • 2020-12-21 04:13

    Go retains no master list of structs, interfaces, or variables at the package level, so what you ask is unfortunately impossible.

    0 讨论(0)
  • 2020-12-21 04:13

    Do you come from some scripting language? It looks so.

    Go has good reasons to propagate to let not slip 'magic' into your code.

    What looks easy at the beginning (have access to all structs, register them automatically somewhere, "saving" coding) will end up in debugging and maintenance nightmare when your project gets larger.

    Then you will have to document and lookup all your lousy conventions and implications. I know what I am talking about, because I went this route several times with ruby and nodejs.

    Instead, if you make everything explicit you get some feature, like renaming the People struct to let the compiler tell you where it is used in your whole code base (and the go compiler is faster than you).

    Such possibilities are invaluable for debugging, testing and refactoring.

    Also it makes your code easy to reason about for your fellow coders and yourself several months after you have written it.

    0 讨论(0)
  • 2020-12-21 04:17

    Using go/importer:

    pkg, err := importer.Default().Import("time")
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    for _, declName := range pkg.Scope().Names() {
        fmt.Println(declName)
    }
    

    (note, this returns an error on the Go Playground).

    0 讨论(0)
提交回复
热议问题