I searched through my random checked out applications to see who calls strings.Compare, and why.
Most of them are mistaken sorting. In gVisor, there is this in a test:
...
cmpopts.SortSlices(func(a, b testEntryEventInfo) bool {
return strings.Compare(string(a.Addr), string(b.Addr)) < 0
}),
...
This pattern shows up a bunch: // Less implements sort.Interface.
func (s fooSlice) Less(i, j int) bool {
return strings.Compare(s[i].Whatever, s[j].Whatever) == -1
}
In Go's Snowflake library, there is this: if strings.Compare(s0, name) != 0 {
t.Error("a file was not downloaded by GET")
}
This is exceedingly interesting to me because you'd expect Compare to cost more than < (it does more stuff), and yet people are somehow baited into writing it. I'm guessing what happens is that people don't know that "<" works for strings, and they reach for strings.Compare, so the documentation is trying to talk them out of a program that doesn't actually make sense. In the case of "!= 0", they just wanted "s0 != name", which I take to mean they had absolutely no idea that strings in Go are comparable at all.All in all, I get the impression that people coming from other languages to Go have different expectations about what the language can do. The documentation for strings.Compare is a logical place to correct them, but it doesn't bother. Just a comment that says "sucks if you use this".
BTW, there were a couple of correct uses. Gazelle has a sort function like this in a few places:
sort.SliceStable(sortedFiles, func(i, j int) bool {
if cmp := strings.Compare(sortedFiles[i].Path, sortedFiles[j].Path); cmp != 0 {
return cmp < 0
}
return sortedFiles[i].DefName < sortedFiles[j].DefName
})
Here they are punished for the inefficiency of strings.Compare; they would actually take advantage of it in the common case where the paths aren't equal over the easier approach of: if xs[i].Path != x[j].Path {
return xs[i].Path < xs[j].Path
}
return xs[i].DefName < xs[j].DefName
Another correct use was in "goja" (a Javascript interpreter), which uses strings.Compare to implement Javascript's <string>.compareTo(<string>). Whether or not Javascript code is using compareTo correctly is an analysis I do not have the energy to do :)