4

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?

3
  • 3
    No, {integer} is deep magic in Rust and a very special case. It's not a real type and is only used as an intermediate in type inference. Commented Aug 13, 2022 at 21:00
  • 1
    num_traits can help consider many numeric types as a whole. Commented Aug 13, 2022 at 21:01
  • 1
    "Because if the implementation for all integer types, is the same why care about the exact type?" because the compiler cannot conclude it's the same. Commented Aug 14, 2022 at 0:55

1 Answer 1

5

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());
}
Sign up to request clarification or add additional context in comments.

2 Comments

And I can use num_traits::Float for the {float} type?
@MarcellPerger, Yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.