To list the content of a directory in Go, you can use the “os.ReadDir()”, “filepath.Walk()”, or “os.File.Readdir()” functions.
Method 1: Using the os.ReadDir() function
The ReadDir() function reads the named directory, returning all its directory entries sorted by filename.
Syntax
func ReadDir(name string) ([]DirEntry, error)
Example
package main
import (
"fmt"
"os"
)
func main() {
dirPath := "../" // The directory you want to list
// Read the contents of the directory
entries, err := os.ReadDir(dirPath)
if err != nil {
fmt.Println("Error reading the directory:", err)
return
}
// Iterate through the directory entries and print their names
for _, entry := range entries {
fmt.Println(entry.Name())
}
}
Output
.DS_Store
env
environment.yml
myenv
new_file.csv
pyvenv.cfg
In this example, we used the os.ReadDir() function to read the contents of a directory (in this case, the current directory represented by “.”). We iterate through the entries and print their names if there are no errors.
Method 2: Using the filepath.Walk() function
The filepath.Walk() is a handy function in Go that can traverse a file tree.
Syntax
func Walk(root string, walkFn WalkFunc) error
Example
package main
import (
"fmt"
"os"
"path/filepath"
)
func visit(files *[]string) filepath.WalkFunc {
return func(path string, info os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
*files = append(*files, path)
return nil
}
}
func main() {
var files []string
root := "." // Start at current directory
err := filepath.Walk(root, visit(&files))
if err != nil {
panic(err)
}
for _, file := range files {
fmt.Println(file)
}
}
Output
Method 3: Using the os.file.Readdir() function
In Go, you can list all files in a directory using the “os.File.Readdir()” function.
Syntax
func (f *File) Readdir(n int) ([]FileInfo, error)
Example
package main
import (
"fmt"
"log"
"os"
)
func main() {
dir, err := os.Open(".") // open current directory
if err != nil {
log.Fatal(err)
}
defer dir.Close()
fileList, err := dir.Readdir(-1) // -1 means return all the FileInfos
if err != nil {
log.Fatal(err)
}
for _, file := range fileList {
fmt.Println(file.Name())
}
}
Output
app.js
app.cs
Pro.R
share
app.cpp
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.