go/ast

Guided tour · Go Tooling · pkg.go.dev →

Go syntax tree. The node types produced by go/parser and consumed by go/format, linters, and refactoring tools.

Walk an AST

ast.Inspect

ast.Inspect(file, func(n ast.Node) bool {
    if fn, ok := n.(*ast.FuncDecl); ok {
        fmt.Println("func", fn.Name.Name)
    }
    return true // keep descending
})

Build nodes by hand

Construct an expression

expr := &ast.BinaryExpr{
    X:  &ast.Ident{Name: "a"},
    Op: token.ADD,
    Y:  &ast.BasicLit{Kind: token.INT, Value: "1"},
}

Common node types

Files, decls, statements, expressions

*ast.File                  // whole file
*ast.FuncDecl / *ast.GenDecl
*ast.TypeSpec / *ast.ValueSpec
*ast.AssignStmt / *ast.IfStmt / *ast.ForStmt
*ast.CallExpr / *ast.SelectorExpr / *ast.Ident