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.

GoData Integrity

Code

gosnippet
35 lines
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

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.