cmp

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2025 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

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 `slices.SortFunc`, making it easy to sort slices of any ordered type.

Example (Sorting a custom type):

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 using cmp.Compare
slices.SortFunc(products, func(a, b Product) int {
	return cmp.Compare(a.Price, b.Price)
})

// products is now sorted by Price: [{2 49.99} {3 74.99} {1 99.99}]

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Clamp added in v0.4.0

func Clamp[T constraints.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 constraints.Ordered](a, b T) int

Compare returns an integer comparing two values. The result will be 0 if a == b, -1 if a < b, and +1 if a > b.

This function is designed to be fully compatible with the standard library's `slices.SortFunc`, making it a convenient tool for sorting slices of any ordered type.

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 Max added in v0.4.0

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

Max returns the larger of a or b.

func Min added in v0.4.0

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

Min returns the smaller of a or b.

Types

This section is empty.

Jump to

Keyboard shortcuts

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