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 ¶
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.
Example ¶
package main
import (
"cmp"
"fmt"
"math"
)
func main() {
fmt.Println(cmp.Compare(1, 2))
fmt.Println(cmp.Compare("a", "aa"))
fmt.Println(cmp.Compare(1.5, 1.5))
fmt.Println(cmp.Compare(math.NaN(), 1.0))
}
Output: -1 -1 0 -1
func Less ¶
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.
Example ¶
package main
import (
"cmp"
"fmt"
"math"
)
func main() {
fmt.Println(cmp.Less(1, 2))
fmt.Println(cmp.Less("a", "aa"))
fmt.Println(cmp.Less(1.0, math.NaN()))
fmt.Println(cmp.Less(math.NaN(), 1.0))
}
Output: true true false true
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 ¶
package main
import (
"cmp"
"fmt"
)
func main() {
// Suppose we have some user input
// that may or may not be an empty string
userInput1 := ""
userInput2 := "some text"
fmt.Println(cmp.Or(userInput1, "default"))
fmt.Println(cmp.Or(userInput2, "default"))
fmt.Println(cmp.Or(userInput1, userInput2, "default"))
}
Output: default some text some text