Paths and walking in Go
filepath joins with the right separator and walks a tree.
func findGoFiles(root string) ([]string, error) {
var found []string
err := filepath.WalkDir(root, func(path string, entry fs.DirEntry,
err error) error {
if err != nil {
return err
}
if entry.IsDir() && entry.Name() == "vendor" {
return fs.SkipDir
}
if filepath.Ext(path) == ".go" {
found = append(found, filepath.Base(path))
}
return nil
})
if err != nil {
return nil, fmt.Errorf("walk %s: %w", root, err)
}
slices.Sort(found)
return found, nil
}
How it works
Joincleans the result; never concatenate with a slash.WalkDiris the fast walk, using directory entries.- Returning fs.SkipDir prunes a subtree.
Keywords and builtins used here
appenderrorfuncifreturnstringvar
The run, in numbers
- Lines
- 21
- Characters to type
- 448
- Tokens
- 128
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 73 seconds.
Step 3 of 3 in Files & IO, step 8 of 26 in Standard library & project layout.