25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →
Listing Files in a Directory in Go
Code Snippet

Listing Files in a Directory in Go

go

The os.ReadDir function provides an efficient way to list the contents of a directory in Go. Introduced in Go 1.16, it returns a slice of DirEntry objects that are sorted by filename, making it easier to work with directory listings than the older ioutil.ReadDir approach.

Each DirEntry provides methods like Name() to get the filename, IsDir() to check if it’s a directory, and Info() to get detailed file information including size and modification time. This design allows you to avoid unnecessary system calls when you only need basic information.

The function is perfect for scenarios where you need to iterate through files, filter by type, or collect file metadata. It’s more efficient than alternatives because it defers expensive operations until needed.

Further Reading: