Documentation
¶
Overview ¶
パッケージcmpは、順序付けられた値を比較するための型と関数に関連するものを提供します。
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Compare ¶
Compareは、
xがyより小さい場合は-1、 xがyと等しい場合は0、 xがyより大きい場合は+1を返します。
浮動小数点型にはNaN(「非数」)値が含まれる場合があります。 NaN値は、任意の非NaN値よりも小さいと見なされ、NaN値はNaN値と等しく、-0.0は0.0と等しいです。
Example ¶
package main
import (
"github.com/shogo82148/std/cmp"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/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 xがyより小さい場合にtrueを報告します。 浮動小数点型にはNaN(「非数」)値が含まれる場合があります。 NaN値は、任意の非NaN値よりも小さいと見なされ、-0.0は0.0より小さくありません(等しいです)。
Example ¶
package main
import (
"github.com/shogo82148/std/cmp"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/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 v1.22.0
func Or[T comparable](vals ...T) T
Orは、ゼロ値でない最初の引数を返します。 引数が非ゼロでない場合、ゼロ値を返します。
Example ¶
package main
import (
"github.com/shogo82148/std/cmp"
"github.com/shogo82148/std/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
Example (Sort) ¶
package main
import (
"github.com/shogo82148/std/cmp"
"github.com/shogo82148/std/fmt"
"github.com/shogo82148/std/slices"
"github.com/shogo82148/std/strings"
)
func main() {
type Order struct {
Product string
Customer string
Price float64
}
orders := []Order{
{"foo", "alice", 1.00},
{"bar", "bob", 3.00},
{"baz", "carol", 4.00},
{"foo", "alice", 2.00},
{"bar", "carol", 1.00},
{"foo", "bob", 4.00},
}
// Sort by customer first, product second, and last by higher price
slices.SortFunc(orders, func(a, b Order) int {
return cmp.Or(
strings.Compare(a.Customer, b.Customer),
strings.Compare(a.Product, b.Product),
cmp.Compare(b.Price, a.Price),
)
})
for _, order := range orders {
fmt.Printf("%s %s %.2f\n", order.Product, order.Customer, order.Price)
}
}
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 < <= >= >演算子をサポートする任意の順序付けられた型を許可する制約です。 もし将来のGoリリースで新しい順序付けられた型が追加された場合、 この制約はそれらを含めるように変更されます。
浮動小数点型にはNaN(「非数」)値が含まれる場合があります。 NaN値と他の値、NaNであろうとなかろうと、比較演算子(==、<など)は常にfalseを報告します。 NaN値を比較する一貫した方法については、 Compare 関数を参照してください。
Click to show internal directories.
Click to hide internal directories.