Standard library / path/filepath
path/filepath.WalkDir()
Visits tree entries in lexical order with a DirEntry callback; does not follow symlink entries. Callback errors can stop or skip traversal. Example uses a disposable temporary workspace. Expected stdout: '.\na.txt\n'.
Formal Syntax & Structure
go syntaxgo
func WalkDir(root string, fn fs.WalkDirFunc) errorParameters & Attributes
| Name | Type | Description |
|---|---|---|
| root | string | Traversal root. |
| fn | fs.WalkDirFunc | Traversal callback. |
Return Value
error
Visits tree entries in lexical order with a DirEntry callback; does not follow symlink entries.
Working Example
Example Snippetgo
package main
import ( "fmt" "io/fs" "os" "path/filepath")
func check(e error) { if e != nil { panic(e) }}func seed() { check(os.WriteFile("a.txt", []byte("abc"), 0600)) }func workspace() func() { root, e := os.MkdirTemp("", "bytemind-go-") check(e) old, e := os.Getwd() check(e) check(os.Chdir(root)) return func() { check(os.Chdir(old)); check(os.RemoveAll(root)) }}func main() { defer workspace()() seed() check(filepath.WalkDir(".", func(p string, d fs.DirEntry, e error) error { if e != nil { return e } fmt.Println(filepath.ToSlash(p)) return nil }))}