9gagger
9gagger

Reputation: 225

Go AST: get all structs

I would like to be able to get all structs. For example, assume we have:

type SomeType struct {
    // ..
}

type someType2 struct {
    //..
}

Our code.

structs := getAllStructs(srcPath)  //gets SomeType and someType2

I have some code which finds all .go files in srcPath and does parser.ParseFile on it.

Is there a way using ast, parser, packages, etc... I can get all structs at once at any scope? What if there is a struct which is not package scoped? How can I get struct declarations also inside the function? Like:

func main() {
    
    type someType3 struct {
        //..
    }

}

Upvotes: 3

Views: 1647

Answers (1)

Thundercat
Thundercat

Reputation: 121149

Parse each file of interest. Inspect the file to find struct types.

fset := token.NewFileSet()
f, err := parser.ParseFile(fset, fileName, nil, 0)
if err != nil {
    log.Fatal(err)
}

// Collect the struct types in this slice.
var structTypes []*ast.StructType

// Use the Inspect function to walk AST looking for struct
// type nodes.
ast.Inspect(f, func(n ast.Node) bool {
    if n, ok := n.(*ast.StructType); ok {
         structTypes = append(structTypes, n)
    }
    return true
})

// The slice structTypes contains all *ast.StructTypes in the file.

Upvotes: 4

Related Questions