← 中文资源

简体中文版本

Maps EqualFunc 比较值

用 maps.EqualFunc 逐键比较两个 map,把值比较交给 slices.Equal,这样嵌套切片按元素相等而不是按引用判断。

阅读英文原文

实现说明

Maps EqualFunc 比较值的核心是函数 main。

使用要点

  • 直接运行文件,输出会带上标签,比如 equal values:、after edit:、key count:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「Maps EqualFunc 比较值」会打印什么?

整个文件跑完,输出行以 equal values:、after edit:、key count: 这类前缀开头。

核心语句

return slices.Equal(x, y)

代码示例

package main

import (
	"fmt"
	"maps"
	"slices"
)

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

	// slice values are not comparable, so EqualFunc takes the comparison
	same := maps.EqualFunc(left, right, func(x, y []int) bool {
		return slices.Equal(x, y)
	})
	fmt.Println("equal values:", same)

	right["b"] = []int{3, 4}
	fmt.Println("after edit:", maps.EqualFunc(left, right, slices.Equal))
	fmt.Println("key count:", len(left), len(right))

	// different key sets short-circuit before the callback runs
	extra := map[string][]int{"a": {1, 2}, "b": {3}, "c": nil}
	fmt.Println("extra key:", maps.EqualFunc(left, extra, slices.Equal))
}