- Published on
Go maps.Copy
maps.Copy is a function from the Go maps package, introduced in Go 1.21, which provides generic utilities for working with maps.
📘 maps.Copy – What it does
func Copy[K comparable, V any](dst, src map[K]V)
- Purpose: Copies key-value pairs from
srcintodst. - If key exists in
dst, the value will be overwritten. - If
dstis nil, a panic occurs. srccan be nil, in which case it does nothing.
✅ Example
package main
import (
"fmt"
"maps"
)
func main() {
src := map[string]int{"a": 1, "b": 2}
dst := map[string]int{"b": 99, "c": 3}
maps.Copy(dst, src)
fmt.Println(dst) // Output: map[a:1 b:2 c:3]
}
- Key
"b"gets overwritten from99to2. - Key
"a"is added. - Key
"c"remains untouched.
⚠️ Notes
- Go version requirement: Must be using Go 1.21 or later.
- It does not return a new map, it modifies
dstin-place. - Use
maps.Cloneif you want to copy into a new map.