MarcellPerger
MarcellPerger

Reputation: 592

How to implement a trait on `{integer}` type in Rust

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?

Upvotes: 4

Views: 3153

Answers (1)

user1635327
user1635327

Reputation: 1641

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());
}

Upvotes: 5

Related Questions