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.

GoCli Tooling

Code

gosnippet
26 lines
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

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:`.