use generic_array::*; // 0.12.3
use num::{Float, Zero}; // 0.2.0
#[derive(Clone, Debug)]
struct Vector<T, N: ArrayLength<T>> {
data: GenericArray<T, N>,
}
impl<T, N: ArrayLength<T>> Vector<T, N>
where
T: Float + Zero,
{
fn dot(&self, other: Self) -> T {
self.data
.iter()
.zip(other.data.iter())
.fold(T::zero(), |acc, x| acc + *x.0 * *x.1)
}
fn length_sq(&self) -> T {
self.dot(self.clone())
}
}
error[E0308]: mismatched types
--> src/lib.rs:21:18
|
21 | self.dot(self.clone())
| ^^^^^^^^^^^^ expected struct `Vector`, found reference
|
= note: expected type `Vector<T, N>`
found type `&Vector<T, N>`
Why does this happen? Why does clone
return &T
instead of T
?
Why does this work if I implement Clone
myself?
use generic_array::*; // 0.12.3
use num::{Float, Zero}; // 0.2.0
#[derive(Debug)]
struct Vector<T, N: ArrayLength<T>> {
data: GenericArray<T, N>,
}
impl<T: Float, N: ArrayLength<T>> Clone for Vector<T, N> {
fn clone(&self) -> Self {
Vector::<T, N> {
data: self.data.clone(),
}
}
}
impl<T, N: ArrayLength<T>> Vector<T, N>
where
T: Float + Zero,
{
fn dot(&self, other: Self) -> T {
self.data
.iter()
.zip(other.data.iter())
.fold(T::zero(), |acc, x| acc + *x.0 * *x.1)
}
fn length_sq(&self) -> T {
self.dot(self.clone())
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…