从包的给定路径中提取类型名称的最简单的工作示例

Jas*_* Xu 4 abstract-syntax-tree go

我是 golang AST 包和相关 go 工具(如 astutils)的新手。目前,我有点困于理解 Stringer 示例并根据自己的目的对其进行修改。

https://github.com/golang/tools/blob/master/cmd/stringer/stringer.go

是否有一个简单地提取包路径中所有已定义类型名称的列表的工作示例?

Ain*_*r-G 5

我想出了这个打印所有(顶级)类型名称的程序示例。解析目录,获取包,然后遍历它。

fs := token.NewFileSet()
pkgs, err := parser.ParseDir(fs, dir, nil, 0)
// Check err.
pkg, ok := pkgs["pkgname"]
// Check ok.
ast.Walk(VisitorFunc(FindTypes), pkg)
Run Code Online (Sandbox Code Playgroud)

其中VisitorFuncFindTypes定义为

type VisitorFunc func(n ast.Node) ast.Visitor

func (f VisitorFunc) Visit(n ast.Node) ast.Visitor { return f(n) }

func FindTypes(n ast.Node) ast.Visitor {
    switch n := n.(type) {
    case *ast.Package:
        return VisitorFunc(FindTypes)
    case *ast.File:
        return VisitorFunc(FindTypes)
    case *ast.GenDecl:
        if n.Tok == token.TYPE {
            return VisitorFunc(FindTypes)
        }
    case *ast.TypeSpec:
        fmt.Println(n.Name.Name)
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)

Playground 上的完整代码:http://play.golang.org/p/Rk_zmrmD0k(由于不允许 FS 操作,因此无法在那里工作)。


编辑:这是一个在 Playground 上运行的版本,由 Ivan Black 在评论中编写: https: //play.golang.org/p/yLV6-asPas