0
0
GoHow-ToBeginner · 3 min read

How to Walk Directory in Go: Simple Guide with Example

In Go, you can walk a directory using filepath.WalkDir which recursively visits all files and folders. You provide a root path and a function that runs on each file or directory found.
📐

Syntax

The basic syntax of filepath.WalkDir is:

  • root: the starting directory path as a string.
  • walkFn: a function called for each file or directory found. It receives the path, directory entry info, and an error.

The function should return an error or nil to continue walking.

go
func WalkDir(root string, fn fs.WalkDirFunc) error
💻

Example

This example walks the current directory and prints each file and folder path.

go
package main

import (
	"fmt"
	"io/fs"
	"log"
	"path/filepath"
)

func main() {
	err := filepath.WalkDir(".", func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		fmt.Println(path)
		return nil
	})

	if err != nil {
		log.Fatal(err)
	}
}
Output
./ ./main.go ./subdir ./subdir/file.txt
⚠️

Common Pitfalls

Common mistakes when walking directories in Go include:

  • Not handling the error passed to the walk function, which can cause silent failures.
  • Returning a non-nil error inside the walk function unintentionally stops the walk.
  • Confusing filepath.Walk (older) with filepath.WalkDir (recommended for Go 1.16+).
go
/* Wrong: ignoring error and returning non-nil error stops walk */
filepath.WalkDir(".", func(path string, d fs.DirEntry, err error) error {
	// ignoring err
	return fmt.Errorf("stop") // stops walking immediately
})

/* Right: handle error and return nil to continue */
filepath.WalkDir(".", func(path string, d fs.DirEntry, err error) error {
	if err != nil {
		return err
	}
	fmt.Println(path)
	return nil
})

Key Takeaways

Use filepath.WalkDir to recursively visit files and directories in Go.
Always handle the error parameter inside the walk function to avoid silent failures.
Return nil from the walk function to continue walking, or an error to stop.
Prefer filepath.WalkDir over filepath.Walk for better performance and features in Go 1.16+.