go / expert
Snippet
Programmatic AST Modification and Code Inspection via Go Parser
Go standard library `go/parser` and `go/ast` packages enable parsing Go source text into an Abstract Syntax Tree (AST). Programmers can traverse node hierarchies using `ast.Inspect` to build custom linters, code generators, or static analysis tools.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package mainimport ("fmt""go/ast""go/parser""go/token")func main() {fset := token.NewFileSet()src := `package sample; func Compute(x int) int { return x + 42 }`node, err := parser.ParseFile(fset, "", src, 0)if err != nil {panic(err)}ast.Inspect(node, func(n ast.Node) bool {if fn, ok := n.(*ast.FuncDecl); ok {fmt.Printf("Discovered function declaration: %s\n", fn.Name.Name)}return true})}
Breakdown
1
fset := token.NewFileSet()
Initializes a position token set to track file offset locations during source AST parsing.
2
node, err := parser.ParseFile(fset, "", src, 0)
Parses raw Go source string into a structured Abstract Syntax Tree node graph.
3
ast.Inspect(node, func(n ast.Node) bool {
Traverses AST nodes depth-first, filtering for specific syntactic constructs such as function declarations.