Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 892
MarcellPerger Avatar asked Nov 01 '25 13:11

MarcellPerger


1 Answers

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());
}
like image 139
user1635327 Avatar answered Nov 03 '25 21:11

user1635327