Golang go/ast.Inspect() function examples
package go/ast
Inspect traverses an AST in depth-first order: It starts by calling f(node); node must not be nil. If f returns true, Inspect invokes f for all the non-nil children of node, recursively.
Golang go/ast.Inspect() function usage examples
Example 1:
type fieldInfo struct {
Name string
IsBasic bool // handled by one the native Read/WriteUint64 etc functions
IsSlice bool // field is a slice of FieldType
FieldType string // original type of field, i.e. "int"
Encoder string // the encoder name, i.e. "Uint64" for Read/WriteUint64
Convert string // what to convert to when encoding, i.e. "uint64"
Max int // max size for slices and strings
}
type structInfo struct {
Name string
Fields []fieldInfo
}
func inspector(structs *[]structInfo) func(ast.Node) bool {
return func(n ast.Node) bool {
switch n := n.(type) {
case *ast.TypeSpec:
switch t := n.Type.(type) {
case *ast.StructType:
name := n.Name.Name
fs := handleStruct(t)
*structs = append(*structs, structInfo{name, fs})
}
return false
default:
return true
}
}
}
func main() {
flag.Parse()
fname := flag.Arg(0)
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, fname, nil, parser.ParseComments)
if err != nil {
panic(err)
}
var structs []structInfo
i := inspector(&structs)
ast.Inspect(f, i) // <--- here
...
}
Example 2:(from http://golang.org/pkg/go/ast/#Inspect )
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
)
func main() {
// src is the input for which we want to inspect the AST.
src := `
package p
const c = 1.0
var X = f(3.14)*2 + c
`
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "src.go", src, 0)
if err != nil {
panic(err)
}
// Inspect the AST and print all identifiers and literals.
ast.Inspect(f, func(n ast.Node) bool {
var s string
switch x := n.(type) {
case *ast.BasicLit:
s = x.Value
case *ast.Ident:
s = x.Name
}
if s != "" {
fmt.Printf("%s:\t%s\n", fset.Position(n.Pos()), s)
}
return true
})
}
References :
Advertisement
Something interesting
Tutorials
+22.9k Golang : Gorilla mux routing example
+35.9k Golang : Integer is between a range
+8.1k Golang : Variadic function arguments sanity check example
+9.1k Golang : How to capture return values from goroutines?
+19.2k Golang : Check if directory exist and create if does not exist
+17.5k Golang : Clone with pointer and modify value
+6.2k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+16.8k Golang : Get own process identifier
+3.6k Java : Get FX sentiment from website example
+11k Golang : Generate random elements without repetition or duplicate
+16.3k Golang : Loop each day of the current month example
+13.7k Golang : Activate web camera and broadcast out base64 encoded images