astrewrite: Index | Examples | Files

package astrewrite

import ""



Package Files


func Walk Uses

func Walk(node ast.Node, fn WalkFunc) ast.Node

Walk traverses an AST in depth-first order: It starts by calling fn(node); node must not be nil. It returns the rewritten node. If fn returns true, Walk invokes fn recursively for each of the non-nil children of node, followed by a call of fn(nil). The returned node of fn can be used to rewrite the passed node to fn. Panics if the returned type is not the same type as the original one.


src := `package main

type Foo struct{}`

fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "foo.go", src, parser.ParseComments)
if err != nil {

rewriteFunc := func(n ast.Node) (ast.Node, bool) {
    x, ok := n.(*ast.TypeSpec)
    if !ok {
        return n, true

    // change struct type name to "Bar"
    x.Name.Name = "Bar"
    return x, true

rewritten := Walk(file, rewriteFunc)

var buf bytes.Buffer
printer.Fprint(&buf, fset, rewritten)


package main

type Bar struct{}

type WalkFunc Uses

type WalkFunc func(ast.Node) (ast.Node, bool)

WalkFunc describes a function to be called for each node during a Walk. The returned node can be used to rewrite the AST. Walking stops if the returned bool is false.

Package astrewrite imports 2 packages (graph) and is imported by 4 packages. Updated 2019-12-12. Refresh now. Tools for package owners.