How to Use the go/ast, go/parser, and go/printer Packages

Parse Go source with go/parser, inspect the tree with go/ast, and regenerate code with go/printer.

Use go/parser to convert source code into an AST, go/ast to inspect or modify that tree, and go/printer to generate valid Go code from the result.

package main

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/printer"
	"go/token"
	"os"
)

func main() {
	fset := token.NewFileSet()
	astFile, err := parser.ParseFile(fset, "main.go", nil, parser.ParseComments)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}

	// Inspect or modify the AST
	ast.Inspect(astFile, func(n ast.Node) bool {
		if fn, ok := n.(*ast.FuncDecl); ok {
			fmt.Println("Found function:", fn.Name.Name)
		}
		return true
	})

	// Print the modified AST back to code
	if err := printer.Fprint(os.Stdout, fset, astFile); err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
}