Int::{min,max} in const fn

Right now, if you want to compute the maximum of two numbers in const context, you have to do an if a < b { b } else { a } manually. This is because usize::max() evaluates to <usize as Ord>::max which is a trait method and hence can't be const.

Could we add inherent methods to the integer types to work around this?

impl usize {
    pub const fn min(self, rhs: Self) -> Self {
        if self > rhs { rhs } else { self }
    }
    pub const fn max(self, rhs: Self) -> Self {
        if self < rhs { rhs } else { self }
    }
}

This way, whenever anyone writes usize::max(a,b) it will evaluate to this method instead, which is const. It shouldn't be a breaking change since this does not change the behavior of anyone calling the trait method.

We could, but I do expect that we'll make Ord a const trait soon.

9 Likes

Maybe is it reasonable to add 2 new methods const_max and const_min to impl usize (and other integer types)?

A lot of trait methods could be useful in const context. Since it's supposed to be a temporary workaround for a missing language feature, it's better to create a crate, say const_trait_workarounds, and later once the feature lands users can drop the dependency. Putting it in std would mean the deprecated workaround stays around forever.

15 Likes

Are const traits actually nearing stabilization? I know there's been a ton of activity on that front but haven't been following it too closely.

8 Likes

Part of the reason I suggest it is that const traits did not seem near stabilization to me. But I have not followed it that closely. But I do not think it's a particularly big technical debt to have a max method on integers. We already have them for f32/f64.

@VitWW I would not call them const_max/const_min. Just call them min/max and let them shadow the trait method.

6 Likes

It looks like there's tracking issues for making specific traits const-callable for specific std-lib types, which would be enough for this and I think will land well before support for const traits on arbitrary library traits/types. Though admittedly I haven't been following the most closely with that effort

3 Likes

In the meantime, you can use const_utils.

2 Likes

The konst crate has more stuff in it.

1 Like