Standard library / go/ast

go/ast.Walk()

Traverses the syntax tree using a Visitor. Returning nil prunes children; a non-nil visitor gets a final Visit(nil). Expected stdout: '3\n'.

Formal Syntax & Structure

go syntaxgo
func Walk(v Visitor, node Node)

Parameters & Attributes

NameTypeDescription
vVisitorVisitor or reflection value, depending on the API.
nodeNodeRoot syntax node to traverse or inspect.

Working Example

Example Snippetgo
package main
import (  "fmt"  "go/ast"  "go/parser")
func check(e error) {  if e != nil {    panic(e)  }}
type counter struct{ n *int }
func (v counter) Visit(n ast.Node) ast.Visitor {  if n != nil {    *v.n++    return v  }  return nil}
func main() {  x, e := parser.ParseExpr("1+2")  check(e)  n := 0  ast.Walk(counter{&n}, x)  fmt.Println(n)}
Go Reference