Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get all struct under a package in Golang?

Tags:

go

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
like image 808
Anthony Tsang Avatar asked Jun 09 '14 10:06

Anthony Tsang


People also ask

How do I import a struct from another package in go?

The struct name in another package must start with a capital letter so that it is public outside its package. If the struct name starts with lowercase then it will not be visible outside its package. To access a struct outside its package we need to import the package first which contains that struct.

How does struct work in Golang?

A structure or struct in Golang is a user-defined type that allows to group/combine items of possibly different types into a single type. Any real-world entity which has some set of properties/fields can be represented as a struct. This concept is generally compared with the classes in object-oriented programming.

Is package main mandatory in Golang?

The main package must have package name main and declare a function main that takes no arguments and returns no value. Program execution begins by initializing the main package and then invoking the function main.


1 Answers

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")
            }
        }
    }
like image 146
VonC Avatar answered Oct 29 '22 06:10

VonC