This question already has an answer here:
I'm learning rust and I can't understand why the following code gives an error.
use std::ops::Mul;
use std::ops::Add;
struct Vec2<T>
{
x: T,
y: T,
}
impl<T: Mul + Add> Vec2<T> {
fn magnitude_squared(&self) -> T {
self.x * self.x + self.y * self.y // error here
}
}
fn main() {
let x = Vec2 { x: 1f32, y: 1f32 };
println!("{}", x.magnitude_squared());
}
Error message (doesn't make much sense to me unless multiplication of two floats produces some 'non-addable' type):
src\main.rs(14,9): error E0369: binary operation
+
cannot be applied to type<T as std::ops::Mul>::Output
help: runrustc --explain E0369
to see a detailed explanation
note: an implementation ofstd::ops::Add
might be missing for<T as std::ops::Mul>::Output
Rust compiler rustc 1.11.0 (9b21dcd6a 2016-08-15)
The code is similar to this example. What's the difference that makes my code wrong?
The error message tells you what to do: you need to add an
Add
implementation for<T as Mul>::Output
.You can do so by adding a trait bound on your
impl
as such:The
Copy
was added to simplify this answer.