Я создал абстрактный тип данных для векторов в метрическом пространстве, но компилятор жалуется, потому что не распознает, что реализация в качестве аргумента относится к этому типу.
trait MetricPoint {
fn square_distance(&self, other: &MetricPoint) -> f64;
}
struct RNPoint {
coordinates: Vec<f64>,
}
impl RNPoint {
fn new(coordinates: &[f64]) -> RNPoint {
RNPoint {
coordinates: coordinates.to_vec(),
}
}
}
impl MetricPoint for RNPoint {
fn square_distance(self: &RNPoint, other: &RNPoint) -> f64 {
let min_len = self.coordinates.len().min(other.coordinates.len());
let mut sum = 0.0;
for i in 0..min_len {
let diff = self.coordinates[i] - other.coordinates[i];
sum += diff * diff;
}
sum
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn square_distance() {
let p1 = RNPoint::new(&[0.0, 0.0]);
let p2 = RNPoint::new(&[1.0, 0.0]);
let d = p1.square_distance(&p2);
assert_eq!(d, 1.0)
}
}
Компилятор:
error[E0053]: method `square_distance` has an incompatible type for trait
--> points/src/lib.rs:19:44
|
2 | fn square_distance(&self, other: &MetricPoint) -> f64;
| ------------ type in trait
...
19 | fn square_distance(self:&RNPoint,other:&RNPoint)->f64 {
| ^^^^^^^^ expected trait MetricPoint, found struct `RNPoint`
|
= note: expected type `fn(&RNPoint, &dyn MetricPoint) -> f64`
found type `fn(&RNPoint, &RNPoint) -> f64`
Почему он не признает, что RNPoint
является MetricPoint
?