A simple working example of retrieving type names from a given package path

I am new to golang AST package and related tools like astutils. At the moment, I am a bit stuck in understanding the Stringer example and changing it for my own purpose.

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

Is there a working example of simply extracting a list of all the defined type names in a package path?

+4
source share
1 answer

I came up with this example program that prints names of all types (top level). Dismantle the catalog, get the package and go through it.

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

Where VisitorFuncand are FindTypesdefined as

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
}

: http://play.golang.org/p/Rk_zmrmD0k ( , FS ).


EDIT: , , : https://play.golang.org/p/yLV6-asPas

+4

All Articles