Go

filepath.Walk — Recursive Tree Walk

admin by @admin ADMIN
Jun 14, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`filepath.WalkDir` (Go 1.16+) is the modern, faster version. Visit every file/dir under a root; the callback decides whether to skip or process.
Go
Raw
package main

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

func main() {
    err := filepath.WalkDir("src", func(path string, d fs.DirEntry, err error) error {
        if err != nil { return err }                  // propagate stat errors

        // Skip hidden directories without descending into them
        if d.IsDir() && strings.HasPrefix(d.Name(), ".") && d.Name() != "." {
            return filepath.SkipDir
        }

        if !d.IsDir() && strings.HasSuffix(path, ".go") {
            fmt.Println(path)
        }
        return nil
    })
    if err != nil { fmt.Println("walk error:", err) }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.