Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all defined types?

Tags:

go

package demo

type People struct {
    Name string
    Age  uint
}

type UserInfo struct {
    Address  string
    Hobby    []string
    NickNage string
}

another package:

import "demo"

in this package, how can I get all the types exported from the demo package?

like image 670
emitle Avatar asked Dec 27 '13 16:12

emitle


4 Answers

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

like image 141
王一帆 Avatar answered Oct 20 '22 15:10

王一帆


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

like image 22
Linear Avatar answered Oct 20 '22 16:10

Linear


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.

like image 20
BraveNewCurrency Avatar answered Oct 20 '22 14:10

BraveNewCurrency


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.

like image 1
metakeule Avatar answered Oct 20 '22 14:10

metakeule