Deep Copy Nested Maps And Slices

Duplicate nested config before mutation with a recursive deep copy over map[string]any and []any, so edited snapshots never touch the original values.

GoData Integrity

Code

gosnippet
42 lines
package main

import "fmt"

// 深拷贝(deep copy)嵌套(nested)值:map 与 slice 各自新建
func deepCopyValue(v any) any {
	switch t := v.(type) {
	case map[string]any:
		out := make(map[string]any, len(t))
		for k, val := range t {
			out[k] = deepCopyValue(val)
		}
		return out
	case []any:
		out := make([]any, len(t))
		for i, val := range t {
			out[i] = deepCopyValue(val)
		}
		return out
	default:
		return v // 标量按不可变值直接共享
	}
}

func main() {
	config := map[string]any{
		"region": "eu-1",
		"limits": map[string]any{"rps": 50, "burst": 100},
		"zones":  []any{"a", "b"},
	}

	// 拿到快照后先断言出具体容器再修改
	snapshot := deepCopyValue(config).(map[string]any)
	limits := snapshot["limits"].(map[string]any)
	limits["rps"] = 999
	zones := snapshot["zones"].([]any)
	zones[0] = "z"

	fmt.Println("snapshot limits:", snapshot["limits"])
	fmt.Println("config limits:", config["limits"])
	fmt.Println("config zones:", config["zones"])
}

How the snippet works

Deep Copy Nested Maps And Slices comes down to the functions deepCopyValue and main.

Iteration happens inside for k, val := range t — everything outside it runs once.

Watch out for

  • Zero-fetch snippet: every identifier resolves inside the language distribution.

Applying it

Entry signature: func deepCopyValue(v any) any

Each run prints the 3 labeled blocks snapshot limits:, config limits:, config zones: in source order.

main sequences deepCopyValue; executing the file runs that flow once.

Statements that matter most here

for k, val := range t {
out[k] = deepCopyValue(val)
}
for i, val := range t {
out[i] = deepCopyValue(val)
}
out := make(map[string]any, len(t))

Interactive Tools for This Topic

FAQ

What does Deep Copy Nested Maps And Slices print when run?
No setup needed: run the file and look for labeled lines like `snapshot limits:`, `config limits:`, `config zones:` in the output.