Package maps

suggest change

The maps package in the standard library has generic functions for things you used to write as loops: copying a map, merging two maps, comparing maps, deleting entries that match a condition, and getting the keys or values.

It was added in Go 1.21. Go 1.23 added functions that return and consume iterators.

function added what it does
Clone(m) 1.21 new map with the same entries (shallow copy)
Copy(dst, src) 1.21 copy all entries of src into dst, overwriting existing keys
Equal(m1, m2) 1.21 same keys with equal values
EqualFunc(m1, m2, eq) 1.21 like Equal, with a function to compare values
DeleteFunc(m, del) 1.21 delete entries for which del(k, v) returns true
All(m) 1.23 iterator over key/value pairs (iter.Seq2[K, V])
Keys(m) 1.23 iterator over keys (iter.Seq[K])
Values(m) 1.23 iterator over values (iter.Seq[V])
Collect(seq) 1.23 new map from an iter.Seq2[K, V]
Insert(m, seq) 1.23 add pairs from an iter.Seq2[K, V] to an existing map

Go 1.21 also added the built-in clear(m) which deletes all entries of a map.

All functions accept any map type, including named types like type Labels map[string]string.

Clone: copy a map

A map value is a pointer to the underlying hash table. Assigning a map, or passing it to a function, doesn't copy the entries: both variables refer to the same map.

maps.Clone returns a new map with the same entries:

package main

import (
	"fmt"
	"maps"
)

func main() {
	prices := map[string]int{"apple": 3, "pear": 4}

	alias := prices             // copies the map header: same map
	clone := maps.Clone(prices) // new map with the same entries

	prices["apple"] = 100

	fmt.Println("prices:", prices)
	fmt.Println("alias: ", alias)
	fmt.Println("clone: ", clone)

	var empty map[string]int
	c := maps.Clone(empty)
	fmt.Println("clone of nil is nil:", c == nil)
}
prices: map[apple:100 pear:4]
alias:  map[apple:100 pear:4]
clone:  map[apple:3 pear:4]
clone of nil is nil: true

maps.Clone(nil) returns nil, not an empty map. Reading from a nil map is fine but writing to it panics, so if you plan to add entries to the clone of a map that might be nil, use make and maps.Copy instead.

Copy a map shows the equivalent for range loop. maps.Clone is shorter and faster: it copies the hash table directly instead of inserting the entries one by one.

Shallow copies

maps.Clone copies the keys and values, but only one level deep. If the values are slices, maps or pointers, the clone shares them with the original:

package main

import (
	"fmt"
	"maps"
	"slices"
)

func main() {
	teams := map[string][]string{
		"backend":  {"ann", "bob"},
		"frontend": {"cid"},
	}

	shallow := maps.Clone(teams)
	shallow["backend"][0] = "ANN" // modifies the shared slice

	// deep copy: clone each value too
	deep := make(map[string][]string, len(teams))
	for k, v := range teams {
		deep[k] = slices.Clone(v)
	}
	deep["frontend"][0] = "CID"

	fmt.Println("teams:  ", teams)
	fmt.Println("shallow:", shallow)
	fmt.Println("deep:   ", deep)
}
teams:   map[backend:[ANN bob] frontend:[cid]]
shallow: map[backend:[ANN bob] frontend:[cid]]
deep:    map[backend:[ANN bob] frontend:[CID]]

Writing shallow["backend"] = newSlice would only change the clone. It's modifying the elements of a shared slice that leaks into the original. See Immutability for more about defensive copies.

Copy: merge maps

maps.Copy(dst, src) copies every entry of src into dst. If a key exists in both, the value from src wins.

A common use is merging user settings over defaults:

package main

import (
	"fmt"
	"maps"
)

func main() {
	defaults := map[string]string{
		"host":    "localhost",
		"port":    "8080",
		"timeout": "30s",
	}
	user := map[string]string{
		"port":  "9000",
		"debug": "true",
	}

	// start from defaults, then let user settings win
	cfg := maps.Clone(defaults)
	maps.Copy(cfg, user)

	fmt.Println(cfg)
	fmt.Println(defaults) // unchanged
}
map[debug:true host:localhost port:9000 timeout:30s]
map[host:localhost port:8080 timeout:30s]

fmt prints map entries sorted by key, which is why the output above is stable. Iterating with range is not ordered.

dst and src can be different map types as long as the key and value types match. dst must not be nil: copying into a nil map panics, just like m[k] = v does:

package main

import (
	"fmt"
	"maps"
)

type Labels map[string]string

func main() {
	src := map[string]string{"env": "prod"}

	defer func() {
		fmt.Println("recovered:", recover())
	}()

	// Copy works between different map types with the same key and value types
	labels := Labels{"app": "api"}
	maps.Copy(labels, src)
	fmt.Println(labels)

	var dst map[string]string
	maps.Copy(dst, src) // panics
}
map[app:api env:prod]
recovered: assignment to entry in nil map

Copying an empty src into a nil dst doesn't panic, because nothing is written. That makes the bug easy to miss in tests.

Equal and EqualFunc: compare maps

Maps can't be compared with == (only to nil). maps.Equal reports whether two maps have the same keys and the same values for each key. Order doesn't matter, and a nil map is equal to an empty map.

maps.Equal requires a comparable value type. For values like slices, or to compare values in a custom way, use maps.EqualFunc. The two maps can even have different value types:

package main

import (
	"fmt"
	"maps"
	"slices"
	"strings"
)

func main() {
	a := map[string]int{"x": 1, "y": 2}
	b := map[string]int{"y": 2, "x": 1}
	fmt.Println(maps.Equal(a, b))

	var nilMap map[string]int
	fmt.Println(maps.Equal(nilMap, map[string]int{}))

	// []string values are not comparable, so Equal doesn't compile;
	// EqualFunc takes a function to compare the values
	tags1 := map[string][]string{"go": {"fast", "simple"}}
	tags2 := map[string][]string{"go": {"fast", "simple"}}
	fmt.Println(maps.EqualFunc(tags1, tags2, slices.Equal[[]string]))

	// the value types can differ: compare int counts to string counts
	counts := map[string]int{"a": 1, "b": 2}
	labels := map[string]string{"a": "1", "b": "2"}
	same := maps.EqualFunc(counts, labels, func(n int, s string) bool {
		return fmt.Sprint(n) == s
	})
	fmt.Println(same)

	// case-insensitive comparison of values
	h1 := map[string]string{"Content-Type": "TEXT/HTML"}
	h2 := map[string]string{"Content-Type": "text/html"}
	fmt.Println(maps.EqualFunc(h1, h2, strings.EqualFold))
}
true
true
true
true
true

Keys are always compared with ==. Equality and comparison covers the comparison rules in detail, including reflect.DeepEqual.

DeleteFunc: remove matching entries

maps.DeleteFunc deletes, in place, every entry for which the function returns true:

package main

import (
	"fmt"
	"maps"
	"slices"
	"time"
)

func main() {
	now := time.Date(2026, 10, 17, 12, 0, 0, 0, time.UTC)
	sessions := map[string]time.Time{
		"alice": now.Add(10 * time.Minute),
		"bob":   now.Add(-5 * time.Minute),
		"carol": now.Add(-1 * time.Hour),
		"dave":  now.Add(2 * time.Hour),
	}

	// delete expired sessions
	maps.DeleteFunc(sessions, func(user string, expires time.Time) bool {
		return expires.Before(now)
	})

	fmt.Println(slices.Sorted(maps.Keys(sessions)))
}
[alice dave]

It's the same as a range loop that calls delete, which is allowed in Go: deleting entries while iterating over a map is safe. If you need to keep the original map, filter into a new map instead (see "Building maps from iterators" below) or clone it first.

clear: delete all entries

The built-in clear(m) deletes all entries. Unlike m = map[K]V{}, it modifies the map itself, so every variable referring to it sees an empty map:

package main

import (
	"fmt"
	"math"
)

func main() {
	cache := map[string]int{"a": 1, "b": 2, "c": 3}
	alias := cache

	clear(cache) // deletes all entries
	fmt.Println(len(cache), len(alias))

	cache["d"] = 4 // the map is still usable (and still shared)
	fmt.Println(alias)

	// NaN keys can't be deleted with delete(), but clear removes them
	m := map[float64]string{}
	m[math.NaN()] = "x"
	m[math.NaN()] = "y" // NaN != NaN, so this is a second entry
	for k := range m {
		delete(m, k) // no-op: the lookup never finds a NaN key
	}
	fmt.Println("after delete:", len(m))
	clear(m)
	fmt.Println("after clear:", len(m))
}
0 0
map[d:4]
after delete: 2
after clear: 0

clear on a nil map does nothing. On a slice, clear zeroes the elements but keeps the length.

Iterating: All, Keys and Values

maps.All, maps.Keys and maps.Values return iterators. You can range over them directly, but their main use is passing a map to functions that accept iterators, like slices.Sorted or slices.Collect.

Iterators over maps have the same random order as range over a map (see Iterate a map with range). slices.Sorted(maps.Keys(m)) is the idiomatic way to get keys in sorted order:

package main

import (
	"fmt"
	"maps"
	"slices"
)

func main() {
	ages := map[string]int{"ann": 31, "bob": 25, "cid": 42, "dan": 25}

	// keys in sorted order
	for _, name := range slices.Sorted(maps.Keys(ages)) {
		fmt.Printf("%s=%d ", name, ages[name])
	}
	fmt.Println()

	// sorted, de-duplicated values
	vals := slices.Compact(slices.Sorted(maps.Values(ages)))
	fmt.Println(vals)

	// maps.All yields key/value pairs, like range over the map
	total := 0
	for _, age := range maps.All(ages) {
		total += age
	}
	fmt.Println("total:", total)
}
ann=31 bob=25 cid=42 dan=25 
[25 31 42]
total: 123

slices.Sorted collects the iterator into a new slice and sorts it (see Package slices for the rest of the slices package). Before Go 1.23 you had to write that loop yourself. To sort by value or with a custom order, see "Sorting map keys" in Sorting.

maps.Keys returns an iterator, not a slice. If you need a slice in random order, use slices.Collect(maps.Keys(m)).

Building maps from iterators: Collect and Insert

maps.Collect builds a new map from any iter.Seq2[K, V]. maps.Insert adds the pairs to an existing map, overwriting keys that already exist.

slices.All yields index/value pairs, so collecting it gives you a map from index to value:

package main

import (
	"fmt"
	"maps"
	"slices"
)

func main() {
	// slices.All yields (index, value): collect it into map[int]string
	colors := []string{"red", "green", "blue"}
	byIndex := maps.Collect(slices.All(colors))
	fmt.Println(byIndex)

	// maps.Collect(maps.All(m)) is another way to clone
	clone := maps.Collect(maps.All(byIndex))
	fmt.Println(maps.Equal(clone, byIndex))

	// maps.Insert adds pairs from an iterator to an existing map
	more := []string{"cyan", "magenta"}
	maps.Insert(byIndex, func(yield func(int, string) bool) {
		for i, c := range more {
			if !yield(len(colors)+i, c) {
				return
			}
		}
	})
	fmt.Println(byIndex)
}
map[0:red 1:green 2:blue]
true
map[0:red 1:green 2:blue 3:cyan 4:magenta]

maps.Insert(dst, maps.All(src)) does the same as maps.Copy(dst, src). Copy is clearer when you have a map; Insert is for when you have an iterator.

Combined with small iterator adapters you can transform maps without intermediate slices. Here Swap inverts a map and Filter keeps some of the entries, producing a new map and leaving the original alone:

package main

import (
	"fmt"
	"iter"
	"maps"
)

// Swap turns a sequence of (k, v) pairs into (v, k) pairs.
func Swap[K, V any](seq iter.Seq2[K, V]) iter.Seq2[V, K] {
	return func(yield func(V, K) bool) {
		for k, v := range seq {
			if !yield(v, k) {
				return
			}
		}
	}
}

// Filter keeps only the pairs for which keep returns true.
func Filter[K, V any](seq iter.Seq2[K, V], keep func(K, V) bool) iter.Seq2[K, V] {
	return func(yield func(K, V) bool) {
		for k, v := range seq {
			if keep(k, v) && !yield(k, v) {
				return
			}
		}
	}
}

func main() {
	codes := map[string]int{"OK": 200, "Not Found": 404, "Teapot": 418, "Bad Gateway": 502}

	byCode := maps.Collect(Swap(maps.All(codes)))
	fmt.Println(byCode[404])

	errors := maps.Collect(Filter(maps.All(codes), func(_ string, c int) bool {
		return c >= 400
	}))
	fmt.Println(errors)
}
Not Found
map[Bad Gateway:502 Not Found:404 Teapot:418]

When inverting a map with duplicate values, several keys map to the same new key and the last one wins. Since iteration order is random, which one survives is random too.

Map, filter, and reduce has more adapters like these.

Maps don't shrink

Deleting entries, with delete, maps.DeleteFunc or clear, doesn't release the memory of the hash table. A map that once held a million entries keeps that memory until the map itself is garbage collected.

maps.Clone doesn't help either: it copies the hash table as is, empty slots included. To shrink a map, create a new one sized for the remaining entries and copy them:

package main

import (
	"fmt"
	"maps"
	"runtime"
)

func heapMB() uint64 {
	runtime.GC()
	var ms runtime.MemStats
	runtime.ReadMemStats(&ms)
	return ms.HeapAlloc / (1 << 20)
}

func main() {
	m := make(map[int][64]byte)
	for i := range 1_000_000 {
		m[i] = [64]byte{}
	}
	fmt.Println("full:        ", heapMB(), "MB")

	// delete all but 10 entries
	maps.DeleteFunc(m, func(k int, _ [64]byte) bool { return k >= 10 })
	fmt.Println("after delete:", heapMB(), "MB, len", len(m))

	// Clone copies the hash table as is, including the empty slots
	m = maps.Clone(m)
	fmt.Println("after Clone: ", heapMB(), "MB")

	// a new map sized for the remaining entries releases the memory
	small := make(map[int][64]byte, len(m))
	maps.Copy(small, m)
	m = small
	fmt.Println("after Copy:  ", heapMB(), "MB, len", len(m))
	runtime.KeepAlive(m)
}
full:         160 MB
after delete: 160 MB, len 10
after Clone:  160 MB
after Copy:   0 MB, len 10

clear is the right choice when you'll refill the map to a similar size, because the memory is reused. For a long-lived map that grew temporarily, replace it with a new map.

Swiss table maps (Go 1.24)

Go 1.24 replaced the implementation of the built-in map with one based on Swiss tables. Entries are stored in groups of 8 slots with a control word of 8 bytes per group, and a lookup checks all 8 slots of a group in parallel using a few bit operations. A large map is split into several independent tables of up to 1024 slots, so growing the map rehashes one small table at a time instead of the whole map.

What this means for your code:

Go 1.24 and 1.25 let you switch back to the old implementation with GOEXPERIMENT=noswissmap. The old implementation has since been removed.

Things to keep in mind

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents