4

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`
2
  • What do you expect the result to be when T is a String?
    – Shepmaster
    Commented Jun 10, 2019 at 12:59
  • By the way, idiomatic Rust uses snake_case for variables, methods, macros, fields and modules; UpperCamelCase for types and enum variants; and SCREAMING_SNAKE_CASE for statics and constants.
    – Shepmaster
    Commented Jun 10, 2019 at 13:09

1 Answer 1

9

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
    }
}
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.