TLDR: I'd like a function in std like cmp(a, b)
that calls a.cmp(b)
.
Recently, std::iter::zip
was added for better readability/formatting when using iterators that are the result of lots of function calls. For example:
let a = vec![1, 2, 3].into_iter();
let b = vec![1, 2, 3].into_iter();
let zipped = a
.map(|i| i * 2)
.filter(|i| i % 3 == 0)
.zip(b.map(|i| i * 2).filter(|i| i % 3 == 0));
// compared to
zip(
a.map(|i| i * 2).filter(|i| i % 3 == 0),
b.map(|i| i * 2).filter(|i| i % 3 == 0),
)
Recently I found myself sorting a lot of slices using .sort_by()
, and this lead to a pretty similar situation with code like:
items.sort_by(|a, b| {
a.config
.properties
.some_value
.cmp(&b.config.properties.some_value)
});
However, with this cmp
function I was able to get similar readability improvements as with zip
.
fn cmp<T>(a: &T, b: &T) -> Ordering where T: Ord {
a.cmp(b)
}
items.sort_by(|a, b| {
cmp(
&a.config.properties.some_value,
&b.config.properties.some_value,
)
})
There's probably scope for an equivalent for partial_cmp
, though I suspect the "symmetry" benefits are less obvious if the two arguments might have different types
I'd be keen to see this in the standard library, and if other people also think it would be a good addition I'd be happy to open a PR for it. But of course if there are reasons why such a function isn't needed, or doesn't belong in std, I'd be more than happy to hear them too.
Thanks