slices Compare Orders Lexicographically

Rank slices element by element with slices.Compare, which reports the first differing element, while CompareFunc applies a custom ordering rule.

GoData Integrity

Code

gosnippet
33 lines
package main

import (
	"fmt"
	"slices"
)

func main() {
	// Compare 按字典序逐元素比较:-1 / 0 / 1 三态结果
	fmt.Println("cmp:", slices.Compare([]int{1, 2, 3}, []int{1, 2, 4}))
	fmt.Println("cmp:", slices.Compare([]string{"go", "rust"}, []string{"go", "rust"}))

	// 前缀更短的一方排在前:长度差异在首个不同元素处决出
	fmt.Println("prefix:", slices.Compare([]int{1, 2}, []int{1, 2, 3}))

	// CompareFunc:自定义比较规则,例如忽略大小写比较字节
	ignoreCase := func(a, b byte) int {
		switch {
		case a|0x20 < b|0x20:
			return -1
		case a|0x20 > b|0x20:
			return 1
		default:
			return 0
		}
	}
	fmt.Println("fold:", slices.CompareFunc([]byte("Hello"), []byte("heLLo"), ignoreCase))

	// 版本分档: Compare 结果直接映射为排序方向
	versions := [][]int{{1, 9}, {1, 10}, {2, 0}}
	slices.SortFunc(versions, slices.Compare)
	fmt.Println("sorted:", versions)
}

Inside the snippet

Structurally, expect the function main and nothing else.

Caveats

  • All of it is standard-library — paste it in and it runs.

Putting it to use

Entry signature: func main()

The demo output is labeled (cmp:, prefix:, fold:), so the printed output reads as a trace of the operations performed.

Core lines under the microscope

versions := [][]int{{1, 9}, {1, 10}, {2, 0}}

Interactive Tools for This Topic

FAQ

What does slices Compare Orders Lexicographically print when run?
The script runs standalone; its 4 labeled outputs include `cmp:`, `prefix:`, `fold:`.