Map Preallocation With Size Hint

make(map[K]V, n) preallocates room for n entries so bulk inserts skip repeated rehash growth, and maps.Copy into a sized map gets the same hint.

GoData Integrity

Code

gosnippet
26 lines
package main

import (
	"fmt"
	"maps"
)

func main() {
	// 已知要写入的键数量时给 make 传容量提示:
	// map 按提示一次性分配空间,插入期间不再反复扩容搬迁
	workers := make(map[string]int, 4)
	workers["orders"] = 3
	workers["billing"] = 1
	workers["auth"] = 9
	workers["search"] = 2

	fmt.Println("len:", len(workers))

	// 把已知规模的 map 拷进新 map,同样先给容量提示
	merged := make(map[string]int, len(workers))
	maps.Copy(merged, workers)
	merged["reports"] = 5

	fmt.Println("orders:", merged["orders"], "reports:", merged["reports"])
	fmt.Println("missing key yields zero value:", merged["nope"])
}

How the snippet works

Every runnable line is contained in the function main.

Caveats

  • No install step: the snippet lives entirely inside the standard library.

Applying it

The main signature is written as func main()

The run emits 3 labeled sections — len:, orders:, missing key yields zero value: — one per step.

Statements that matter most here

merged := make(map[string]int, len(workers))
workers := make(map[string]int, 4)

Interactive Tools for This Topic

FAQ

What does Map Preallocation With Size Hint print when run?
Execute the whole file; each printed line is prefixed with a label like `len:`, `orders:`, `missing key yields zero value:`.