Go: Copy nested slices when cloning a map
A map copy can have independent keys while still sharing mutable values. maps.Clone copies each value by assignment, so a slice value continues to refer to the same backing array. Clone the slices too when edits to a copied configuration must stay local.
Set up
Tested on Linux amd64 with Go 1.26.10. Use Bash with Go on your PATH, a text editor, and the mktemp, rm, and rmdir utilities. The example uses only the standard library. Keep the same terminal through cleanup, and stop if setup fails before saving the source.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as go-maps-clone-nested-slices.go:
package main
import (
"fmt"
"maps"
"slices"
)
func cloneGroups(input map[string][]string) map[string][]string {
result := maps.Clone(input)
for key, values := range result {
result[key] = slices.Clone(values)
}
return result
}
func main() {
original := map[string][]string{"team": {"read", "write"}}
shallow := maps.Clone(original)
shallow["team"][0] = "changed"
shallow["extra"] = []string{"review"}
_, extraPresent := original["extra"]
fmt.Printf("after shallow edit: original=%q extra=%t\n", original["team"], extraPresent)
owned := cloneGroups(original)
owned["team"][0] = "isolated"
fmt.Printf("after nested copy: original=%q copy=%q\n", original["team"], owned["team"])
var absent map[string][]string
fmt.Println("nil preserved:", cloneGroups(absent) == nil)
}Run:
go run go-maps-clone-nested-slices.goObserved output:
after shallow edit: original=["changed" "write"] extra=false
after nested copy: original=["changed" "write"] copy=["isolated" "write"]
nil preserved: trueRead the result
Adding a key to the shallow copy leaves the original map unchanged. Editing the first slice element changes both maps because that element lives in shared storage. The helper copies the map and then replaces each slice value with a clone.
The nested copy starts after the deliberate shallow edit, so it inherits the already changed value. Its later edit stays isolated. The helper also preserves a nil input map; the loop over it has no entries.
Apply it carefully
The helper is specific to a map of string slices. Strings are immutable, so copying each slice’s elements separates the mutable data in this shape. A map of slices of pointers, or of structs with more maps and slices inside them, needs a copying policy for those nested values as well.
Take the copy while the source is stable, or protect the map and its slice contents with appropriate synchronization. Cloning does not make concurrent writes safe. A preserved nil result remains a nil map: initialize it before adding new keys if the caller needs a writable empty configuration.
See maps.Clone and slices.Clone.
Clean up
Remove the saved source and the empty scratch directory. Go manages its build cache separately. If the directory is not empty, inspect its contents before removing anything else.
rm -- go-maps-clone-nested-slices.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.