Traverse and rewrite AST nodes
Traverse and rewrite AST nodes
An AST transformation changes syntax nodes instead of replacing arbitrary substrings. Use ast.Inspect for traversal; returning false skips a subtree. Mutate a field only after checking its concrete node type and context. This example replaces a particular numeric literal in a known declaration; it is not a general rename engine.
package main
import ( "fmt" "go/ast" "go/format" "go/parser" "go/token" "os")
func main() { fs := token.NewFileSet() f, e := parser.ParseFile(fs, "p.go", `package pconst Limit = 10`, parser.ParseComments) if e != nil { panic(e) } ast.Inspect(f, func(n ast.Node) bool { v, ok := n.(*ast.ValueSpec) if ok && len(v.Names) == 1 && v.Names[0].Name == "Limit" && len(v.Values) == 1 { if lit, ok := v.Values[0].(*ast.BasicLit); ok && lit.Kind == token.INT { lit.Value = "20" } } return true }) if e := format.Node(os.Stdout, fs, f); e != nil { panic(e) } fmt.Print("")}Only the initializer of Limit is changed. Printing the tree reconstructs formatted source. Real transformations must preserve relevant comments (use ParseComments and consider ast.CommentMap), reparse and type-check the result. A syntactically valid edit may still change meaning or introduce a type error.
Expected output:
package p
const Limit = 20Skip function bodies for a declaration inventory
package main
import ( "fmt" "go/ast" "go/parser" "go/token")
func main() { f, e := parser.ParseFile(token.NewFileSet(), "p.go", "package p; var Global=1; func work(){local:=2;_=local}", 0) if e != nil { panic(e) } ast.Inspect(f, func(n ast.Node) bool { switch x := n.(type) { case *ast.FuncDecl: fmt.Println("func", x.Name.Name) return false case *ast.ValueSpec: for _, id := range x.Names { fmt.Println("value", id.Name) } } return true })}The local variable is deliberately excluded. Returning false on the function node prunes its children; the walk still visits sibling declarations. Replacing entire nodes requires access to the parent field or a traversal library such as astutil.Apply (external x/tools, not executed here).
Expected output:
value Globalfunc workTry it locally
Parse package p; const A=1; const B=2 and change only B to 3, then format the file.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Developer tooling 02: Traverse and rewrite AST nodes
Check the lesson objective before moving on.
What does false from ast.Inspect mean?
What must follow a nontrivial AST edit?