Parse Go Source With go parser

Parse Go source text into a syntax tree with go/parser, then walk it with ast.Inspect to report every function declaration and its parameter count.

GoCli Tooling

Code

gosnippet
43 lines
package main

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"strings"
)

func main() {
	// 待解析源码:一行一条拼成完整文件
	lines := []string{
		"package inventory",
		"",
		"func price(qty int, cents int) int {",
		"\treturn qty * cents",
		"}",
		"",
		"func main() {",
		"\tprintln(price(2, 450))",
		"}",
	}
	src := strings.Join(lines, "\n")

	fset := token.NewFileSet()
	file, err := parser.ParseFile(fset, "demo.go", src, 0)
	if err != nil {
		fmt.Println("parse error:", err)
		return
	}
	fmt.Println("package:", file.Name.Name)

	// ast.Inspect 深度优先遍历:命中函数声明时报出名字与参数个数
	ast.Inspect(file, func(n ast.Node) bool {
		fn, ok := n.(*ast.FuncDecl)
		if !ok {
			return true
		}
		fmt.Printf("func %s params=%d\n", fn.Name.Name, fn.Type.Params.NumFields())
		return true
	})
}

How the pieces connect

What shifts state lives in the functions main and price.

err is inspected at 1 call site before any result is trusted.

Points of care

  • Nothing to set up: the platform already ships every API used.

Applying it

The main signature reads func main()

Output lines are prefixed (parse error:, package:, func), holding every step and its printed line together.

The demo flow inside main is price — run the file to see it end to end.

Statements that matter

"func price(qty int, cents int) int {",
"\treturn qty * cents",
"}",
"func main() {",
"\tprintln(price(2, 450))",
"}",
if err != nil {
fmt.Println("parse error:", err)
return
}

Interactive Tools for This Topic

FAQ

What does Parse Go Source With go parser print when run?
Run it as a complete program — the output lines carry labels such as `parse error:`, `package:`, `func`.