Generic integer MAX


I want to have a function generic over an integer type T, and be able to access its MIN/MAX constants. But apparently they're not bound to any trait.
Is there a way to access <T>::MAX where T: integer (sortof) ?

The standard library doesn't have numeric traits, but you can use the num crate's Bounded trait.


Oh nice, I just made my own crate for this, but using associated constants instead of methods. I guess it's useless, won't publish it.

Just in case someone wants to avoid importing a whole crate for this, and just copy/paste instead:

pub trait MinMax {
    const MIN: Self;
    const MAX: Self;

impl MinMax for u8 {
    const MIN: u8 = u8::MIN;
    const MAX: u8 = u8::MAX;

/* etc. */

mod tests {
    fn it_works<T>()
        T: super::MinMax + std::fmt::Debug + std::cmp::Eq + std::ops::Div<Output = T>,
        std::num::Wrapping<T>: std::ops::Add<std::num::Wrapping<T>, Output = std::num::Wrapping<T>>,
        // FIXME
        let one = T::MAX / T::MAX;

            (std::num::Wrapping(T::MAX) + std::num::Wrapping(one)).0
    fn it_works_u8() {
/* etc. */

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.