Standard library / go/ast

go/ast.Inspect()

Visits nodes depth first. Returning false prunes a subtree; a successful visit is followed by a nil callback after its children. Expected stdout: '1\n2\n'.

Formal Syntax & Structure

go syntaxgo
func Inspect(node Node, f func(Node) bool)

Parameters & Attributes

NameTypeDescription
nodeNodeRoot syntax node to traverse or inspect.
ffunc(Node) boolPredicate or callback controlling traversal, filtering or printing, as described above.

Working Example

Example Snippetgo
package main
import (  "fmt"  "go/ast"  "go/parser")
func check(e error) {  if e != nil {    panic(e)  }}
func main() {  x, e := parser.ParseExpr("1+2")  check(e)  ast.Inspect(x, func(n ast.Node) bool {    if lit, ok := n.(*ast.BasicLit); ok {      fmt.Println(lit.Value)    }    return true  })}
Go Reference