Skip to content

Go Directories

Working with directories is a core part of many Go applications. You'll primarily use the os package for these tasks.

1. Basic Operations

package main

import (
    "fmt"
    "os"
)

func main() {
    // 1. Create a single directory
    err := os.Mkdir("subdir", 0755)
    if err != nil {
        fmt.Println(err)
    }

    // 2. Create nested directories (like `mkdir -p`)
    err = os.MkdirAll("a/b/c", 0755)

    // 3. Remove a directory (must be empty)
    os.Remove("subdir")

    // 4. Remove a directory and all its contents (like `rm -rf`)
    os.RemoveAll("a")
}

2. Listing Directory Contents

Use os.ReadDir to get a list of files and folders inside a directory.

1
2
3
4
5
entries, _ := os.ReadDir(".")

for _, entry := range entries {
    fmt.Println(entry.Name(), entry.IsDir())
}

3. Change Working Directory

You can change where your program searches for files using Chdir.

1
2
3
os.Chdir("/tmp")
cwd, _ := os.Getwd()
fmt.Println("Current dir:", cwd)

Linux Permission Codes (The 0755)

When creating directories or files, Go uses numeric permission codes (octal).

Code Meaning
0755 Everyone can read/execute; only owner can write. (Standard for folders)
0644 Everyone can read; only owner can write. (Standard for files)
0700 Only the owner can do anything. (Private)
0777 Everyone can do everything. (Not recommended)

Why use MkdirAll?

It is "idempotent." If the directory already exists, it doesn't return an error; it just does nothing. This makes it safer for setup scripts.