如何将1加到通用T?

时间:2019-06-10 12:43:08

标签: rust

以下是通用类型Foo。如何正确实现addOne方法:

struct Foo<T> {
    n: T,
}

impl<T> Foo<T> {
    fn addOne(self) -> T {
        self.n + 1
    }
}

fn main() {
    let a = Foo { n: 5 };
    println!("{}", a.addOne());
}

我希望输出为6,但是此代码无法编译:

error[E0369]: binary operation `+` cannot be applied to type `T`
 --> src/main.rs:7:16
  |
7 |         self.n + 1
  |         ------ ^ - {integer}
  |         |
  |         T
  |
  = note: `T` might need a bound for `std::ops::Add`

1 个答案:

答案 0 :(得分:7)

您可以借助num板条箱进行操作:

use num::One; // 0.2.0
use std::ops::Add;

struct Foo<T: Add<T>> {
    n: T,
}

impl<T> Foo<T>
where
    T: Add<Output = T> + One,
{
    fn addOne(self) -> T {
        self.n + One::one()
    }
}

fn main() {
    let a = Foo { n: 5 };
    println!("{}", a.addOne());
}

您可以通过实现自己的One作为练习来做同样的事情,但这需要很多样板代码:

trait One {
    fn one() -> Self;
}

// Now do the same for the rest of the numeric types such as u8, i8, u16, i16, etc
impl One for i32 {
    fn one() -> Self {
       1
    }
}