Go
10 Sep 2026
6 min read
Compare Go Slices Lexicographically with slices.Compare
Sometimes equality isn’t enough. You may need to order version components, compare path segments, choose which byte sequence comes first, or sort records by a slice-valued key. Writing that comparison by hand is straightforward, but the prefix case and the meaning of the return value are easy places to introduce small bugs. For slices whose element type is ordered, slices.Compare provides the standard lexicographic comparison directly. It compares elements from left to right and, when all shared elements match, treats the shorter slice as smaller.