Slices Equal And EqualFunc Predicate

Compare slices for equality with slices.Equal and swap in a per-pair predicate via EqualFunc for case-insensitive matches.

GoData Integrity

Code

gosnippet
24 lines
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]))
}

How the snippet works

Slices Equal And EqualFunc Predicate is built around the function main.

Using it

The demo output is labeled (equal:, reordered:, case-fold equal:); each label names the call that printed it.

Key statements

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

Interactive Tools for This Topic

FAQ

What does Slices Equal And EqualFunc Predicate print when run?
Invoke the file as-is — the `equal:`, `reordered:`, `case-fold equal:` prefixes identify which step printed each line.