os Readdirnames Lists Directory Names
os.File.Readdirnames returns entry names without FileInfo allocations, a cheaper listing when the code only needs what a directory contains.
Code
package main
import (
"fmt"
"os"
)
func main() {
dir, err := os.Open(".")
if err != nil {
panic(err)
}
defer dir.Close()
// Readdirnames lists names only: no FileInfo allocations per entry
names, err := dir.Readdirnames(-1)
if err != nil {
panic(err)
}
if len(names) == 0 {
fmt.Println("empty directory")
return
}
fmt.Println("entries:", len(names))
fmt.Println("first:", names[0])
}Inside the snippet
Structurally, expect the function main and nothing else.
Nothing continues past an unchecked error — 2 if err != nil branches, each ending in panic(err). Cleanup is attached with defer, so it runs on every exit path of the function.
Caveats
- All of it is standard-library — paste it in and it runs.
- Adapting this to library code usually means replacing the
panic(err)calls with error returns the caller can branch on.
Putting it to use
Entry signature: func main()
Look for the empty directory, entries:, first: prefixes during the file’s run; they match each line of output to the step that emitted it.
Core lines under the microscope
if err != nil {
panic(err)
}
defer dir.Close()
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.
FAQ
- What happens when a call fails?
- There are no error returns here: a non-nil `err` reaches `panic(err)` immediately.
- What does os Readdirnames Lists Directory Names print when run?
- The script runs standalone; its 3 labeled outputs include `empty directory`, `entries:`, `first:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.