Below is a generic type Foo
. How can I correctly implement the addOne
method:
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());
}
I expect the output of 6, but this code does not compile:
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`
You can do it with the help of the num
crate:
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());
}
You can do the same by implementing your own One
as an exercise, but it requires a lot of boilerplate code:
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With