MkdirAll Creates Nested Directories

Create a whole nested directory chain in one call with os.MkdirAll, rely on its idempotence for repeat calls, and clean up the tree with os.RemoveAll.

GoData Integrity

Code

gosnippet
33 lines
package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func main() {
	root, err := os.MkdirTemp("", "demo-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(root)

	nested := filepath.Join(root, "deploy", "2026-11-19", "assets")

	// 一次调用创建整条嵌套目录链
	if err := os.MkdirAll(nested, 0o755); err != nil {
		panic(err)
	}
	info, err := os.Stat(nested)
	if err != nil {
		panic(err)
	}
	fmt.Println("created dir:", info.IsDir(), filepath.Base(nested))

	// 重复调用是幂等的:目录已存在不报错
	if err := os.MkdirAll(nested, 0o755); err != nil {
		panic(err)
	}
	fmt.Println("second MkdirAll: ok")
}

How it works

MkdirAll Creates Nested Directories keeps everything in the function main.

Every err != nil branch (4 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state. Deferred at entry, executed at exit: defer keeps cleanup adjacent to acquisition.

What to watch for

  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Putting it to use

The demo output is labeled (created dir:, second MkdirAll: ok); each label names the call that printed it.

Core lines

if err != nil {
	panic(err)
}
defer os.RemoveAll(root)

Interactive Tools for This Topic

FAQ

What is the error handling style?
The failure path is `panic(err)` — detected problems halt the run rather than being passed back.
What does MkdirAll Creates Nested Directories print when run?
Invoke the file as-is — the `created dir:`, `second MkdirAll: ok` prefixes identify which step printed each line.