Nil Map Reads Versus Writes

Show which nil map operations are safe — len and comma-ok lookup — and which one panics on assignment, then allocate with make before writing.

GoData Integrity

Code

gosnippet
29 lines
package main

import "fmt"

func main() {
	// 只声明不 make:settings 是 nil map
	var settings map[string]string

	// 读(read)操作安全:len、comma-ok 查找都表现得像空 map
	fmt.Println("len:", len(settings))
	if env, ok := settings["env"]; ok {
		fmt.Println("env:", env)
	} else {
		fmt.Println("env key missing")
	}

	// 写(write)才是雷区:向 nil map 赋值会 panic
	func() {
		defer func() {
			fmt.Println("write panic:", recover())
		}()
		settings["env"] = "prod"
	}()

	// make 分配之后才能写入
	settings = make(map[string]string, 2)
	settings["env"] = "prod"
	fmt.Println("len after make:", len(settings), "env:", settings["env"])
}

Runtime behavior

Nil Map Reads Versus Writes is built around the function main.

defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

Applying it

The run emits 5 labeled sections — len:, env:, env key missing, write panic:, len after make: — one per step.

Statements that matter

defer func() {
	fmt.Println("write panic:", recover())
}()
settings = make(map[string]string, 2)

Interactive Tools for This Topic

FAQ

What does Nil Map Reads Versus Writes print when run?
The script runs standalone; its 5 labeled outputs include `len:`, `env:`, `env key missing`.