我希望能够获取所有结构。例如,假设我们有:
type SomeType struct {
// ..
}
type someType2 struct {
//..
}
我们的代码。
structs := getAllStructs(srcPath) //gets SomeType and someType2
我有一些代码可以找到 srcPath 中的所有 .go 文件并对其执行 parser.ParseFile
。
有没有办法使用 ast , parser , packages等等...我可以在任何范围内一次获取所有结构吗?如果有一个不在包范围内的结构怎么办?我怎样才能在函数内部获得结构声明?喜欢:
func main() {
type someType3 struct {
//..
}
}
最佳答案
Parse每个感兴趣的文件。 Inspect查找结构类型的文件。
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.
关于转到 AST : get all structs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72959643/