cmp.Compare And cmp.Or Build Comparators
Compose multi-key ordering with cmp.Compare inside cmp.Or: the first non-equal field decides, and equal elements keep their relative input order.
Code
package main
import (
"cmp"
"fmt"
"slices"
)
type product struct {
name string
price int // 单位:分
stock int
}
func main() {
items := []product{
{name: "lamp", price: 1999},
{name: "desk", price: 8800},
{name: "lamp", price: 1250},
{name: "chair", price: 4400},
}
// cmp.Or 依次取第一个非零比较结果:价格相同再用名字分胜负
slices.SortStableFunc(items, func(a, b product) int {
return cmp.Or(
cmp.Compare(a.price, b.price),
cmp.Compare(a.name, b.name),
)
})
for _, p := range items {
fmt.Printf("%s %d
", p.name, p.price)
}
}How the file behaves
cmp.Compare And cmp.Or Build Comparators comes down to the function main.
A single loop drives the file — for _, p := range items.
What to watch for
- No external packages — everything leans on the language’s built-in APIs.
Using it
Signature: func main()
Key statements
for _, p := range items {
fmt.Printf("%s %d
", p.name, p.price)
}
return cmp.Or(
cmp.Compare(a.price, b.price),
cmp.Compare(a.name, b.name),
)
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.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.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
- How do you run cmp.Compare And cmp.Or Build Comparators?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.