Maps Package Clone Equal And Comma Ok Lookup

Probe map keys with the comma-ok idiom, then lean on maps.Clone, maps.Equal, and maps.DeleteFunc for copying, comparing, and pruning.

GoData Integrity

Code

gosnippet
32 lines
package main

import (
	"fmt"
	"maps"
)

func main() {
	prices := map[string]int{"widget": 199, "gadget": 499}

	// comma-ok lookup:区分「键不存在」与「值为零值」
	if v, ok := prices["widget"]; ok {
		fmt.Println("widget:", v)
	}
	if v, ok := prices["secret"]; !ok {
		fmt.Println("secret missing, zero value:", v)
	}

	// Clone:与源表彻底独立,互不影响
	snapshot := maps.Clone(prices)
	prices["widget"] = 999
	fmt.Println("clone unaffected:", snapshot["widget"])
	fmt.Println("source mutated:", prices["widget"])

	// Equal:逐键逐值深度比较
	other := map[string]int{"widget": 199, "gadget": 499}
	fmt.Println("equal:", maps.Equal(snapshot, other))

	// 按谓词删除键值对
	maps.DeleteFunc(snapshot, func(k string, v int) bool { return v > 300 })
	fmt.Println("after delete:", snapshot)
}

A walk through the file

Maps Package Clone Equal And Comma Ok Lookup keeps everything in the function main.

Applying it

The run emits 6 labeled sections — widget:, secret missing, zero value:, clone unaffected:, source mutated:, equal:, after delete: — one per step.

Statements that matter

maps.DeleteFunc(snapshot, func(k string, v int) bool { return v > 300 })

Interactive Tools for This Topic

FAQ

What does Maps Package Clone Equal And Comma Ok Lookup print when run?
Invoke the file as-is — the `widget:`, `secret missing, zero value:`, `clone unaffected:` prefixes identify which step printed each line.