Standard library / io/fs

fs.WalkDir()

Visits the root and descendants in lexical order, passes errors to callback, and does not follow symlinks found within directories. Reads directory entries before descent. Expected stdout: '.\na.txt\nsub\nsub/b.txt\n'.

Formal Syntax & Structure

go syntaxgo
func WalkDir(fsys FS, root string, fn WalkDirFunc) error

Parameters & Attributes

NameTypeDescription
fsysFSFilesystem implementing fs.FS.
rootstringRoot path within the filesystem.
fnWalkDirFuncCallback for each visited entry or error.

Return Value

error

Visits the root and descendants in lexical order, passes errors to callback, and does not follow symlinks found within directories.

Working Example

Example Snippetgo
package main
import (  "fmt"  "io/fs"  "testing/fstest"  "time")
func tree() fstest.MapFS {  return fstest.MapFS{"a.txt": &fstest.MapFile{Data: []byte("ok"), Mode: 0644, ModTime: time.Date(2024, 1, 2, 0, 0, 0, 0, time.UTC)}, "sub/b.txt": &fstest.MapFile{Data: []byte("go"), Mode: 0644}}}func main() {  e := fs.WalkDir(tree(), ".", func(p string, d fs.DirEntry, e error) error {    if e != nil {      return e    }    fmt.Println(p)    return nil  })  if e != nil {    panic(e)  }}
Go Reference