I have struct defined like this
struct Shape<T> {
line_one: T,
line_two: T,
}
I am trying to create a simple trait and implementation that takes this struct to calculate some simple math.
My trait and impls look like this
trait Calculate<T: Mul<Output = T>> {
fn calc(&self, Shape: T) -> T;
}
impl<T> Calculate<T> for Shape<T> {
fn calc(&self, Shape: T) -> T {
self.line_one * 2 + self.line_two * 2
}
}
impl Calculate<i32> {
fn calc(&self) -> i32 {
self.line_one * 2 + self.line_two * 2
}
}
fn calc_fn<T: Calculate<i32>>(calculate: T) {
calculate.calc();
}
When I put this into the Rust playground, the compile fails as Mul
is not implemented in the impl Calculate<T>
. However, if I change <T>
to <T: Mul<Output = T>>
, I get the error that
<anon>:14:21: 14:22 error: expected one of `!`, `(`, `+`, `,`, `::`, `<`, or `>`, found `:`
<anon>:14 impl <T> Calculate<T: Mul<Output = T>> for Shape<T>
I'm at a loss as how to implement Mul
for T
in impl Calculate<T>
.
What I'm trying to achieve is code that I can send either a f32
or i32
in without needing to create two different impl definitions so can just pass in T
.