← 中文资源

简体中文版本

cmp.Compare 与 cmp.Or 组合比较器

cmp.Compare 负责单字段比较,cmp.Or 取第一个非零结果:多键排序一行写完;相等时保持输入的相对顺序,语义清晰可组合。

阅读英文原文

实现说明

cmp.Compare 与 cmp.Or 组合比较器可以归结为函数 main。 for _, p := range items 承担全部的逐项处理。

常见问题

「cmp.Compare 与 cmp.Or 组合比较器」这个示例怎么运行?

把它当完整程序编译/解释运行即可——不需要先安装任何东西。

核心语句

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),
)

代码示例

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)
	}
}