maps.Clone, maps.Copy
func Clone[M ~map[K]V, K comparable, V any](m M) M
func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2)Clone a map by assigning its keys and values, or copy pairs into an existing map. Clone is shallow.
| Parameter | Description |
|---|---|
m | The map to clone. Clone of a nil map is nil. |
dst, src | Copy adds every key/value pair from src to dst. A key already present in dst is overwritten. |
Returns: Clone returns the new map. Copy has no return value.
- After Clone, changing cloned["a"][0] also changes orig["a"][0] when the value is a slice. Assigning cloned["b"] = ... does not add "b" to orig.
- Copy does not delete keys that are present in dst but absent from src.
package main
import (
"fmt"
"maps"
)
func main() {
orig := map[string][]int{"a": {1}}
cloned := maps.Clone(orig)
cloned["a"][0] = 9
cloned["b"] = []int{2}
fmt.Println(orig["a"], cloned["a"], orig["b"] == nil, cloned["b"])
dst := map[string]int{"a": 1, "keep": 2}
maps.Copy(dst, map[string]int{"a": 9, "c": 3})
for _, k := range []string{"a", "c", "keep"} {
fmt.Printf("%s=%d\n", k, dst[k])
}
fmt.Println(maps.Clone(map[string]int(nil)) == nil)
}Expected output
[9] [9] true [2]
a=9
c=3
keep=2
true