Standard library / path/filepath
path/filepath.Walk()
Visits a tree in lexical order using FileInfo callbacks; does not follow symbolic links. WalkDir usually avoids extra metadata calls. Example uses a disposable temporary workspace. Expected stdout: '.\na.txt\n'.
Formal Syntax & Structure
go syntaxgo
func Walk(root string, fn WalkFunc) errorParameters & Attributes
| Name | Type | Description |
|---|---|---|
| root | string | Traversal root. |
| fn | WalkFunc | Traversal callback. |
Return Value
error
Visits a tree in lexical order using FileInfo callbacks; does not follow symbolic links.
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.Walk(".", func(p string, i fs.FileInfo, e error) error { if e != nil { return e } fmt.Println(filepath.ToSlash(p)) return nil }))}