I'm trying to implement generics within my library using the num crate Float
trait, but I'm stuck fighting the compiler. This works:
struct Vector<T> {
data: Vec<T>,
}
trait Metric<T> {
fn norm(&self) -> T;
}
impl Metric<f32> for Vector<f32> {
fn norm(&self) -> f32 {
let mut s = 0.0;
for u in &self.data {
s = s + u * u;
}
s.sqrt()
}
}
But this doesn't:
use num::Float; // 0.2.0
struct Vector<T> {
data: Vec<T>,
}
trait Metric<T> {
fn norm(&self) -> T;
}
impl<T: Float> Metric<T> for Vector<T> {
fn norm(&self) -> T {
let mut s = T::zero();
for u in &self.data {
s = s + u * u;
}
s.sqrt()
}
}
The latter gives me the following error:
error[E0369]: binary operation `*` cannot be applied to type `&T`
--> src/lib.rs:16:23
|
16 | s = s + u * u;
| - ^ - &T
| |
| &T
|
= note: an implementation of `std::ops::Mul` might be missing for `&T`
If I remove the reference and iterate over self.data
instead, I get a
error[E0507]: cannot move out of borrowed content
--> src/lib.rs:15:18
|
15 | for u in self.data {
| ^^^^^^^^^ cannot move out of borrowed content