简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM