Is there a way to implement a trait for {integer} type (or all integer types). Because (as a minimal example):
pub trait X {
    fn y();
}
impl<T> X for T {
    fn y() {
        println!("called");
    }
}
fn main() {
    (32).y();
}
gives an error:
error[E0689]: can't call method `y` on ambiguous numeric type `{integer}`
  --> src/main.rs:12:10
   |
12 |     (32).y();
   |          ^
   |
help: you must specify a concrete type for this numeric value, like `i32`
   |
12 |     (32_i32).y();
   |      ~~~~~~
For more information about this error, try `rustc --explain E0689`.
Is there a way to implement trait X for any integer type so that it can be used on any integer (even the ambiguous {integer} type)? Because if the implementation for all integer types, is the same why care about the exact type?
It is possible to bound type T by num_traits::PrimInt like this:
use num_traits::PrimInt;
trait Trait {
    fn y(self) -> Self;
}
impl<T: PrimInt> Trait for T {
    fn y(self) -> Self {
        println!("called");
        return self;
    }
}
fn main() {
    let x = 32;
    println!("{}", x.y());
}
                        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