cmp

package
v0.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2025 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

Package cmp contains generated code by adptool.

Package cmp provides generic, type-safe functions for comparing ordered types.

This package offers fundamental comparison utilities like Min, Max, and Clamp. Its central function, Compare, is designed to be fully compatible with the standard library's `slices.SortFunc`, making it easy to sort slices of any ordered type.

Usage

Sorting a slice of structs by a specific field:

type Product struct {
	ID    int
	Price float64
}

products := []Product{
	{ID: 1, Price: 99.99},
	{ID: 2, Price: 49.99},
	{ID: 3, Price: 74.99},
}

// Sort products by price in ascending order.
slices.SortFunc(products, func(a, b Product) int {
	return cmp.Compare(a.Price, b.Price)
})

Multi-level sorting with custom logic:

type Employee struct {
	Department string
	Seniority  int
	Name       string
}

// Sort employees by Department (A-Z), then Seniority (descending), then Name (A-Z).
func SortEmployees(employees []Employee) {
	slices.SortFunc(employees, func(a, b Employee) int {
		if res := cmp.Compare(a.Department, b.Department); res != 0 {
			return res
		}
		if res := cmp.Compare(b.Seniority, a.Seniority); res != 0 { // Note b, a for descending
			return res
		}
		return cmp.Compare(a.Name, b.Name)
	})
}

For more details, refer to the function documentation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Clamp added in v0.4.0

func Clamp[T Ordered](v, lo, hi T) T

Clamp returns v clamped to the inclusive range [lo, hi]. If v is less than lo, it returns lo. If v is greater than hi, it returns hi. Otherwise, it returns v.

func Compare added in v0.4.0

func Compare[T cmp.Ordered](x, y T) int

func IsZero

func IsZero[T comparable](v T) bool

IsZero returns true if v is the zero value for its type. It is a generic-safe way to check for zero values.

func Less added in v0.13.0

func Less[T cmp.Ordered](x, y T) bool

func Max added in v0.4.0

func Max[T Ordered](a, b T) T

Max returns the larger of a or b.

func Min added in v0.4.0

func Min[T Ordered](a, b T) T

Min returns the smaller of a or b.

func Or

func Or[T comparable](vals ...T) T

Types

type Ordered added in v0.13.0

type Ordered = cmp.Ordered

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL