Standard library / go/parser
go/parser.ParseDir()
Parses .go files in a directory, optionally filtered. Groups by package name; not a build-tag-aware package loader. Expected stdout: '1 1\n'.
Formal Syntax & Structure
go syntaxgo
func ParseDir(fset *token.FileSet, path string, filter func(fs.FileInfo) bool, mode Mode) (pkgs map[string]*ast.Package, first error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| fset | *token.FileSet | Non-nil file set that records source positions. |
| path | string | Directory containing Go source files. |
| filter | func(fs.FileInfo) bool | Optional file predicate; nil accepts all Go files. |
| mode | Mode | Bit flags controlling the scanner or parser. |
Return Value
(pkgs map[string]*ast.Package, first error)
Parses .
Working Example
Example Snippetgo
package main
import ( "fmt" "go/parser" "go/token" "os" "path/filepath")
func check(e error) { if e != nil { panic(e) }}
func main() { d, e := os.MkdirTemp("", "parse-demo") check(e) defer os.RemoveAll(d) check(os.WriteFile(filepath.Join(d, "a.go"), []byte("package demo"), 0600)) pkgs, e := parser.ParseDir(token.NewFileSet(), d, nil, parser.SkipObjectResolution) check(e) fmt.Println(len(pkgs), len(pkgs["demo"].Files))}