konst

Macro max_by

Source
macro_rules! max_by {
    ($left:expr, $right:expr, $($comparator:tt)*) => { ... };
}
Available on crate feature cmp only.
Expand description

Const equivalent of std::cmp::max_by

Returns the $right argument if both compare equal.

ยงExample

// passing a pseudo-closure as the comparator
const AAA: u32 = konst::max_by!(3u32, 10, |&l, &r| konst::const_cmp!(l, r / 4));
assert_eq!(AAA, 3);

// Both arguments compare equal, so the second argument (`6`) is returned.
const MAX_OF_EQ: u32 = konst::max_by!(12, 6, |l: &u32, r| konst::const_cmp!(*l % 3, *r % 3));
assert_eq!(MAX_OF_EQ, 6);

const fn cmp_len(l: &str, r: &str) -> std::cmp::Ordering {
    konst::const_cmp!(l.len(), r.len())
}

// passing a function as the comparator
const BBB: &str = konst::max_by!("he", "bar", cmp_len);
assert_eq!(BBB, "bar");