I get error if use a generic realization for a generic structure. How should I explain to the compiler that the last
function returns data which can be used in subtraction operation?
use std::ops::Sub;
struct Container<A, B>(A, B);
trait Contains {
type A;
type B;
fn contains(&self, &Self::A, &Self::B) -> bool;
fn first(&self) -> Self::A;
fn last(&self) -> Self::B;
}
impl<C: PartialEq, D: PartialEq + Sub> Contains for Container<C, D> {
type A = C;
type B = D;
fn contains(&self, number_1: &Self::A, number_2: &Self::B) -> bool {
(&self.0 == number_1) && (&self.1 == number_2)
}
fn first(&self) -> Self::A {
self.0
}
fn last(&self) -> Self::B {
self.1
}
}
fn difference<C: Contains>(container: &C) -> i32 {
container.last() - container.first()
}
fn main() {
let number_1 = 3;
let number_2 = 10;
let container = Container(number_1, number_2);
println!("Does container contain {} and {}: {}",
&number_1,
&number_2,
container.contains(&number_1, &number_2));
println!("First number: {}", container.first());
println!("Last number: {}", container.last());
println!("The difference is: {}", difference(&container));
}
I get an error:
error[E0369]: binary operation `-` cannot be applied to type `<C as Contains>::B`
--> src/main.rs:30:5
|
30 | container.last() - container.first()
| ^^^^^^^^^^^^^^^^
|
= note: an implementation of `std::ops::Sub` might be missing for `<C as Contains>::B`