cmp

package standard library
go1.24.0 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2025 License: BSD-3-Clause Imports: 0 Imported by: 4,401

Documentation

Overview

Package cmp provides types and functions related to comparing ordered values.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Compare

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

Compare returns

-1 if x is less than y,
 0 if x equals y,
+1 if x is greater than y.

For floating-point types, a NaN is considered less than any non-NaN, a NaN is considered equal to a NaN, and -0.0 is equal to 0.0.

func Less

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

Less reports whether x is less than y. For floating-point types, a NaN is considered less than any non-NaN, and -0.0 is not less than (is equal to) 0.0.

func Or added in go1.22.0

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

Or returns the first of its arguments that is not equal to the zero value. If no argument is non-zero, it returns the zero value.

Example
Output:

default
some text
some text
Example (Sort)
Output:

foo alice 2.00
foo alice 1.00
bar bob 3.00
foo bob 4.00
bar carol 1.00
baz carol 4.00

Types

type Ordered

type Ordered interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
		~float32 | ~float64 |
		~string
}

Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >. If future releases of Go add new ordered types, this constraint will be modified to include them.

Note that floating-point types may contain NaN ("not-a-number") values. An operator such as == or < will always report false when comparing a NaN value with any other value, NaN or not. See the Compare function for a consistent way to compare NaN values.

Jump to

Keyboard shortcuts

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