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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text Diff ComparisonCompare two text blocks line by line and visualize the differences with added, removed, and unchanged lines highlighted. Useful for reviewing changes and patches.
FAQ
- What does slices Compare Orders Lexicographically print when run?
- The script runs standalone; its 4 labeled outputs include `cmp:`, `prefix:`, `fold:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.