Closed
Description
From rust-lang/rust#34774:
This seems like an obvious and missing function from std::cmp::Ordering
:
impl Ordering {
pub fn then(self, other: Ordering) -> Ordering {
match self {
Ordering::Equal => other,
o => o,
}
}
pub fn and_then<F: FnOnce() -> Ordering>(self, other: F) -> Ordering {
match self {
Ordering::Equal => other(),
o => o,
}
}
}
This is useful for creating comparators which do lexicographic order. The second variant allows for skipping the order calculation if it is not necessary.
To explain the name then
/ and_then
: Java has a similar function for comparators, called thenComparing
. The idea is that you can read a comparison function like
self.name.cmp(other.name).then(self.address.cmp(other.address))
as "compare by name, then by address". The then
/ and_then
difference with a closure is inspired by Rust's function names for Option
like or
(by value) / or_else
(by closure).