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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.