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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With