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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.SPDX License LookupSearch common SPDX license identifiers and see permissions, conditions, limitations, copyleft strength, and OSI or FSF approval status.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.