WalkDir Traverses Trees And SkipDir Prunes
Walk a directory tree with filepath.WalkDir, tally files by extension, and return fs.SkipDir on dot-prefixed directories to prune hidden subtrees.
Code
package main
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
)
func main() {
root, err := os.MkdirTemp("", "walkdemo-")
if err != nil {
panic(err)
}
defer os.RemoveAll(root)
// 造一棵小树:两个可见目录、一个以点开头的隐藏目录
files := []string{"src/main.go", "src/util/util.go", "docs/README.md", ".git/HEAD"}
for _, rel := range files {
full := filepath.Join(root, rel)
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
panic(err)
}
if err := os.WriteFile(full, []byte("x"), 0o644); err != nil {
panic(err)
}
}
counts := map[string]int{}
err = filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
// 返回 fs.SkipDir:跳过整个目录,隐藏目录不进统计
if strings.HasPrefix(entry.Name(), ".") && path != root {
return fs.SkipDir
}
return nil
}
counts[filepath.Ext(path)]++
return nil
})
if err != nil {
panic(err)
}
fmt.Println("counts:", counts)
fmt.Println("total:", counts[".go"]+counts[".md"])
}The behavior in sequence
WalkDir Traverses Trees And SkipDir Prunes reduces to the function main.
Iteration happens inside for _, rel := range files — everything outside it runs once. The Go idiom runs throughout — 5 if err != nil checks, each handling the failure on the spot. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
What to watch for
- There are no exceptions to catch —
errreturn values must be checked at each call site.
Using it
The demo output is labeled (counts:, total:), and each printed line traces back to the operation that emitted it.
Key statements
for _, rel := range files {
full := filepath.Join(root, rel)
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
panic(err)
}
if err := os.WriteFile(full, []byte("x"), 0o644); err != nil {
panic(err)
}
}
if err != nil {
panic(err)
}
if err != nil {
return err
}
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.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does the snippet panic on failure?
- As returned `error` values — 5 sites in the snippet check `err` before using other results.
- What does WalkDir Traverses Trees And SkipDir Prunes print when run?
- Run it as a complete program — the output lines carry labels such as `counts:`, `total:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.