The name `T` is already used for a generic parameter

Viewed 277

The following doesn't compile :

fn main() {
    let add = Calculation { num1: 2, num2: 10 };
    println!("{}", Calculation::addition(&add));
}

#[derive(Debug)]
struct Calculation<T> {
    num1: T,
    num2: T,
}

impl<T> Calculation<T>{
    fn addition<T>(&self) -> &T {
        &self.num1 + &self.num2
    }
}

and gives me the following error:

the name `T` is already used for a generic parameter

What could possibly be wrong?

1 Answers

Since Calculation there is no need for addition to be generic:

use std::ops::Add;

#[derive(Debug)]
struct Calculation<T> {
    num1: T,
    num2: T,
}

impl<T> Calculation<T>
where
    T: Add<Output = T> + Copy
{
    fn addition(&self) -> T {
        self.num1 + self.num2
    }
}
Related