6
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?

Dave C
  • 7,729
  • 4
  • 49
  • 65
emitle
  • 323
  • 2
  • 4
  • 8
  • 1
    What are you trying to achieve? – Paul Hankin Dec 28 '13 at 08:36
  • If you need it programmatically, you'd probably want to use `parser` as the answers below say. If you just want it for your own information, you can use the `go doc` command or godoc.org – Tyler Dec 28 '13 at 08:44
  • possible duplicate(it has more and better answers): https://stackoverflow.com/questions/32132064/how-to-discover-all-package-types-at-runtime – quant2016 Sep 01 '21 at 20:57

4 Answers4

5

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

Dave C
  • 7,729
  • 4
  • 49
  • 65
王一帆
  • 51
  • 1
  • 1
3

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

Linear
  • 21,074
  • 4
  • 59
  • 70
1

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.

BraveNewCurrency
  • 12,654
  • 2
  • 42
  • 50
1

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.

metakeule
  • 3,724
  • 2
  • 23
  • 29
  • 2
    have access to all structs doesn't mean you want to register them automatically. There are reasons like code generation. – vimdude Mar 09 '15 at 18:40
  • 1
    @vimdude for code generation you can use the go parser to get all structs of a package and make use of the go:generate flag. – metakeule Mar 10 '15 at 06:33