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.

GoCli Tooling

Code

gosnippet
51 lines
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 — err return 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

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:`.