← 中文资源

简体中文版本

slices.Equal 与 EqualFunc 相等判断

slices.Equal 逐元素按序比较且要求长度一致,顺序不同即为不等;EqualFunc 换成自定义谓词,可做大小写不敏感的相等判断。

阅读英文原文

实现说明

slices.Equal 与 EqualFunc 相等判断可以归结为函数 main。

使用要点

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

常见问题

运行「slices.Equal 与 EqualFunc 相等判断」会打印什么?

运行文件本身,equal:、reordered:、case-fold equal: 这些前缀各对应一段演示逻辑。

核心语句

caseFold := slices.EqualFunc(left, []string{"ORDERS", "Billing"}, strings.EqualFold)

代码示例

package main

import (
	"fmt"
	"slices"
	"strings"
)

func main() {
	left := []string{"orders", "billing"}
	right := []string{"orders", "billing"}
	other := []string{"billing", "orders"}

	// Equal compares element by element in order; EqualFunc swaps in a custom predicate per pair
	fmt.Println("equal:", slices.Equal(left, right))
	fmt.Println("reordered:", slices.Equal(left, other))

	// EqualFunc compares with a predicate instead of ==, here case-insensitive
	caseFold := slices.EqualFunc(left, []string{"ORDERS", "Billing"}, strings.EqualFold)
	fmt.Println("case-fold equal:", caseFold)

	// different lengths are never equal, even with a shared prefix
	fmt.Println("prefix:", slices.Equal(left, left[:1]))
}