Maps Copy Merge And Deep Equal

Clone and merge maps with the maps package and compare nested structures with reflect.DeepEqual so shared-reference bugs surface immediately.

GoData Integrity

Code

gosnippet
24 lines
package main

import (
	"fmt"
	"maps"
	"reflect"
)

func main() {
	base := map[string]int{"a": 1, "b": 2}

	// Clone:彻底分离底层数据,写入副本不影响原表
	clone := maps.Clone(base)
	clone["a"] = 99
	fmt.Println("base a:", base["a"], "clone a:", clone["a"])

	// Insert:把 overlay 并进 base(overlay 优先)
	overlay := map[string]int{"b": 20, "c": 30}
	maps.Insert(base, maps.All(overlay))
	fmt.Println("merged:", base)

	// DeepEqual:值级比较(键序无关)
	fmt.Println("deep equal:", reflect.DeepEqual(base, map[string]int{"a": 99, "b": 20, "c": 30}))
}

The statements in play

Count the function main as the entire surface area of Maps Copy Merge And Deep Equal.

Using it

The demo output is labeled (base a:, merged:, deep equal:), so each line traces straight back to the statement that printed it.

Key statements

overlay := map[string]int{"b": 20, "c": 30}

Interactive Tools for This Topic

FAQ

What does Maps Copy Merge And Deep Equal print when run?
Execute the whole file; each printed line is prefixed with a label like `base a:`, `merged:`, `deep equal:`.