Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the Rust standard library have a Min/Max trait?

Tags:

rust

I want to initialize a variable of type T with its minimum value like T::min(). Is it possible in Rust 1.40.0 without needing an external dependency?

An alternative approach is to set the variable to be None, but this introduces an overhead of None checking each time I want to increment the variable.

like image 647
Hossain Adnan Avatar asked Jan 22 '20 22:01

Hossain Adnan


1 Answers

There are no such traits in the standard library.

However, it is possible to have a generic concept of min and max for arbitrary types without external dependencies if you are willing to create appropriate traits and implement them for the types you are interested in, for example:

use core::fmt::Display;

trait Min {
    fn min() -> Self;
}

trait Max {
    fn max() -> Self;
}

impl Min for u8 {
    fn min() -> u8 {
        std::u8::MIN
    }
}

impl Max for u8 {
    fn max() -> u8 {
        std::u8::MAX
    }
}

impl Min for i32 {
    fn min() -> i32 {
        std::i32::MIN
    }
}

impl Max for i32 {
    fn max() -> i32 {
        std::i32::MAX
    }
}

fn print_min_max<T: Min + Max + Display>() {
    println!("{} -> {}", T::min(), T::max());
}

fn main() {
    let m: i32 = Min::min();
    println!("{}", m);

    print_min_max::<u8>();
    print_min_max::<i32>();
}

This prints:

-2147483648
0 -> 255
-2147483648 -> 2147483647

Playground

like image 157
SirDarius Avatar answered Nov 12 '22 17:11

SirDarius