8

Can we list all struct in the form of name or interface, under a package? Like:

struct := list("fmt")

expected result:

Formatter
GoStringer
Scanner
State
Stringer
Anthony Tsang
  • 345
  • 1
  • 4
  • 13
  • 3
    possible duplicate of [How to get all defined struct in golang?](http://stackoverflow.com/questions/20803758/how-to-get-all-defined-struct-in-golang) – Linear Jun 09 '14 at 10:41
  • 1
    Go doesn't provide this kind of reflection. You cannot make assumptions about symbol names and generally stuff that you don't actually use. – fuz Jun 09 '14 at 11:57

1 Answers1

3

The best you can do is parse the go sources (which you can clone: hg clone https://code.google.com/p/go/), and isolate the ast.StructType.

That is what a pretty printer does:

func (P *Printer) Type(t *AST.Type) int {
    separator := semicolon;

    switch t.form {

    case AST.STRUCT, AST.INTERFACE:
            switch t.form {
            case AST.STRUCT: P.String(t.pos, "struct");
            case AST.INTERFACE: P.String(t.pos, "interface");
            }
            if t.list != nil {
                    P.separator = blank;
                    P.Fields(t.list, t.end);
            }
            separator = none;

In the same idea, the linter go/lint does the same in lint.go:

    case *ast.StructType:
        for _, f := range v.Fields.List {
            for _, id := range f.Names {
                check(id, "struct field")
            }
        }
    }
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Like this way, but seems really dirty and unofficial. – Anthony Tsang Jun 09 '14 at 13:22
  • 2
    @AnthonyTsang no, the linter uses the official way to list structures. This isn't "dirty", this is a consequence of how the language is done, as explained in http://stackoverflow.com/a/22222911/6309. – VonC Jun 09 '14 at 13:25
  • 2
    maybe I should expand more my use case. I am from PHP which is so dynamic that allows me to do almost anything. So I was wounding if I can do it in Golang. I want to list all structs under a package and init them and use them. My use case exactly is "What looks easy at the beginning will end up in debugging and maintenance nightmare". Therefore, I need to stop here and design again. – Anthony Tsang Jun 10 '14 at 03:40