Retrieving the Structure of a Package in Golang
Can we enumerate all structures contained within a GoLang package as a list of names or interfaces?
For instance:
struct := list("fmt")
Expected output:
Formatter GoStringer Scanner State Stringer
The most optimal approach involves parsing the Go source code (which can be cloned using the command hg clone https://code.google.com/p/go/), specifically extracting the ast.StructType instances.
This process is exemplified in pretty printers:
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;
Along similar lines, the go/lint tool performs a similar function in lint.go:
case *ast.StructType: for _, f := range v.Fields.List { for _, id := range f.Names { check(id, "struct field") } }
The above is the detailed content of How to Extract the Structure of a GoLang Package?. For more information, please follow other related articles on the PHP Chinese website!