slices.Compare Lexicographic Ordering

Order two slices element by element with slices.Compare and CompareFunc: -1, 0, or 1 falls out of a lexicographic walk.

GoData Integrity

Code

snippet
package main

import (
	"fmt"
	"slices"
)

func main() {
	// Compare 返回 -1/0/1:逐元素比较,先到差异者定胜负
	fmt.Println(slices.Compare([]int{1, 2, 3}, []int{1, 2, 4}))
	fmt.Println(slices.Compare([]int{1, 2, 3}, []int{1, 2, 3}))
	fmt.Println(slices.Compare([]int{1, 2}, []int{1, 2, 3}))

	// CompareFunc:换自定义元素比较(按长度)
	byLen := func(a, b string) int { return len(a) - len(b) }
	fmt.Println("by length:", slices.CompareFunc([]string{"ab", "x"}, []string{"cd", "y"}, byLen))
}

Reading the code as it runs

The working surface is the function main — everything else is wiring.

Watch out for

  • The dependency list is empty; the language runtime covers it all.

Applying it

The callable everything leans on: func main()

Output lines are prefixed (by length:), so the origin of each printed line is never in doubt.

Statements that matter

byLen := func(a, b string) int { return len(a) - len(b) }

Interactive Tools for This Topic

FAQ

What does slices.Compare Lexicographic Ordering print when run?
Invoke the file as-is — the `by length:` prefixes identify which step printed each line.