以下是通用类型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`
答案 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
}
}