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.
Code
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
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.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.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.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.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.