从包的给定路径中提取类型名称的最简单的工作示例
Simplest working example of extracting Type names from given path of package
我是 golang AST 包和相关的 go 工具(如 astutils)的新手。目前,我有点难以理解 Stringer 示例并根据自己的目的对其进行修改。
https://github.com/golang/tools/blob/master/cmd/stringer/stringer.go
是否有简单提取包路径中所有已定义类型名称列表的工作示例?
我想出了一个打印所有(顶级)类型名称的程序示例。解析目录,获取包,走走
fs := token.NewFileSet()
pkgs, err := parser.ParseDir(fs, dir, nil, 0)
// Check err.
pkg, ok := pkgs["pkgname"]
// Check ok.
ast.Walk(VisitorFunc(FindTypes), pkg)
其中 VisitorFunc
和 FindTypes
定义为
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
}
Playground 上的完整代码:http://play.golang.org/p/Rk_zmrmD0k(由于不允许 FS 操作,因此无法在那里工作)。
编辑: 这是在 Playground 上运行的版本,由 Ivan Black 在评论中提供:https://play.golang.org/p/yLV6-asPas
我是 golang AST 包和相关的 go 工具(如 astutils)的新手。目前,我有点难以理解 Stringer 示例并根据自己的目的对其进行修改。
https://github.com/golang/tools/blob/master/cmd/stringer/stringer.go
是否有简单提取包路径中所有已定义类型名称列表的工作示例?
我想出了一个打印所有(顶级)类型名称的程序示例。解析目录,获取包,走走
fs := token.NewFileSet()
pkgs, err := parser.ParseDir(fs, dir, nil, 0)
// Check err.
pkg, ok := pkgs["pkgname"]
// Check ok.
ast.Walk(VisitorFunc(FindTypes), pkg)
其中 VisitorFunc
和 FindTypes
定义为
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
}
Playground 上的完整代码:http://play.golang.org/p/Rk_zmrmD0k(由于不允许 FS 操作,因此无法在那里工作)。
编辑: 这是在 Playground 上运行的版本,由 Ivan Black 在评论中提供:https://play.golang.org/p/yLV6-asPas